logger-timer
Version:
A quick shortcut to adding a bunch of timers and dumping their deltas.
62 lines • 2.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggerTimer = void 0;
class LoggerTimer {
timerStarts = {};
timerStops = {};
// used to toggler if this loggertimer should track anything
// you probably want this in dev mode, but not in prod mode
isActive;
// used to filter out timer dumps by a minimum value
dumpThreshold;
constructor(opts = { isActive: true, dumpThreshold: 0 }) {
this.isActive = opts.isActive;
this.dumpThreshold = opts.dumpThreshold;
}
// start a timer with a name
startTimer(timerName) {
// can't start timers if not active
if (!this.isActive)
return;
// can't start a started timer
if (this.timerStarts[timerName])
throw new Error(`Timer ${timerName} has already been started!`);
this.timerStarts[timerName] = Date.now();
}
stopTimer(timerName) {
// not that it should matter, but it doesn't hurt to be thorough
if (!this.isActive)
return;
// if a timer hasn't been started, it can't be stopped
if (!this.timerStarts[timerName])
throw new Error(`Timer ${timerName} has not been started!`);
// just some sanity checking
if (this.timerStops[timerName])
throw new Error(`Timer ${timerName} has already been stopped!`);
this.timerStops[timerName] = Date.now();
}
// just in case someone wants to reuse a timer instance
setActive(isActive) {
this.isActive = isActive;
}
getTimerDeltas() {
const deltas = {};
// only iterate over timerStops because we don't care about unstopped timers
Object.keys(this.timerStops).forEach((timerKey) => {
deltas[timerKey] = this.timerStops[timerKey] - this.timerStarts[timerKey];
});
return deltas;
}
// dump the timers in a nice format, default to console.info
dumpTimers(cb = console.info) {
const deltas = this.getTimerDeltas();
Object.keys(deltas).forEach((timerName) => {
const delta = deltas[timerName];
if (delta < this.dumpThreshold)
return;
cb(`[${delta}ms] ${timerName}`);
});
}
}
exports.LoggerTimer = LoggerTimer;
//# sourceMappingURL=LoggerTimer.js.map