import {Tags} from '../../util';
import {TimerWrapper, TimerWrapperFactory} from '../timed';
import {ConsoleMetric, ConsoleMetricOptions} from './metric';
export class ConsoleTimer<T> extends ConsoleMetric implements TimerWrapper<T> {
constructor(
name: string,
tags: Tags,
options: ConsoleMetricOptions,
) {
super(name, tags, options, 'timer');
}
wrap(func: (...args: unknown[]) => T): (...args: unknown[]) => T {
const _console = this.console;
const label = this.fqn;
return function consoleTimerWrapper(...args: unknown[]): T {
_console.time(label);
let result: T;
try {
result = func(...args);
Iif (result instanceof Promise) {
result.then(result => {
_console.timeEnd(label);
return result;
}).catch(err => {
_console.timeEnd(label);
return err;
});
}
else {
_console.timeEnd(label);
}
}
catch (error) {
_console.timeEnd(label);
throw error;
}
return result;
};
}
}
export class ConsoleTimerFactory implements TimerWrapperFactory {
protected readonly options: ConsoleMetricOptions;
constructor(options: ConsoleMetricOptions) {
this.options = { ...options };
}
asyncTimer<T>(name: string, tags: Tags = {}): TimerWrapper<Promise<T>> {
return new ConsoleTimer(name, tags, this.options);
}
timer<T>(name: string, tags: Tags = {}): TimerWrapper<T> {
return new ConsoleTimer(name, tags, this.options);
}
}
|