46 lines
762 B
JavaScript
46 lines
762 B
JavaScript
|
|
'use strict';
|
||
|
|
|
||
|
|
const counters = {};
|
||
|
|
const listeners = [];
|
||
|
|
|
||
|
|
function increment(name, amount) {
|
||
|
|
amount = amount || 1;
|
||
|
|
counters[name] = (counters[name] || 0) + amount;
|
||
|
|
for (const listener of listeners) {
|
||
|
|
listener(name, counters[name]);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function get(name) {
|
||
|
|
return counters[name] || 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
function snapshot() {
|
||
|
|
return Object.assign({}, counters);
|
||
|
|
}
|
||
|
|
|
||
|
|
function reset() {
|
||
|
|
for (const key of Object.keys(counters)) {
|
||
|
|
counters[key] = 0;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function onUpdate(fn) {
|
||
|
|
listeners.push(fn);
|
||
|
|
}
|
||
|
|
|
||
|
|
function startPeriodicLog(intervalMs) {
|
||
|
|
return setInterval(() => {
|
||
|
|
console.log('[metrics]', JSON.stringify(snapshot()));
|
||
|
|
}, intervalMs || 30000);
|
||
|
|
}
|
||
|
|
|
||
|
|
module.exports = {
|
||
|
|
increment,
|
||
|
|
get,
|
||
|
|
snapshot,
|
||
|
|
reset,
|
||
|
|
onUpdate,
|
||
|
|
startPeriodicLog,
|
||
|
|
};
|