3 /** @module cytube-common/metrics/metrics */
5 const MEM_RSS
= 'memory:rss';
6 const LOAD_1MIN
= 'load:1min';
7 const TIMESTAMP
= 'time';
8 const logger
= require('@calzoneman/jsli')('metrics');
11 var reportInterval
= null;
13 let warnedNoReporter
= false;
15 function warnNoReporter() {
16 if (!warnedNoReporter
) {
17 warnedNoReporter
= true;
18 logger
.warn('No metrics reporter configured. Metrics will not be recorded.');
23 * Increment a metrics counter by the specified amount.
25 * @param {string} counter name of the counter to increment
26 * @param {number} value optional value to increment by (default 1)
28 export function incCounter(counter
, amount
= 1) {
29 if (delegate
=== null) {
32 delegate
.incCounter(counter
, amount
);
37 * Start a timer. Returns a handle to use to end the timer.
39 * @param {string} timer name
40 * @return {object} timer handle
42 export function startTimer(timer
) {
45 hrtime
: process
.hrtime()
50 * Stop a timer and record the time (as an average)
52 * @param {object} handle timer handle to Stop
54 export function stopTimer(handle
) {
55 if (delegate
=== null) {
59 const [seconds
, ns
] = process
.hrtime(handle
.hrtime
);
60 delegate
.addTime(handle
.timer
, seconds
*1e3
+ ns
/1e6
);
64 * Add a property to the current metrics period.
66 * @param {string} property property name to add
67 * @param {any} property value
69 export function addProperty(property
, value
) {
70 if (delegate
=== null) {
73 delegate
.addProperty(property
, value
);
78 * Set the metrics reporter to record to.
80 * @param {MetricsReporter} reporter reporter to record metrics to
82 export function setReporter(reporter
) {
87 * Set the interval at which to report metrics.
89 * @param {number} interval time in milliseconds between successive reports
91 export function setReportInterval(interval
) {
92 clearInterval(reportInterval
);
93 if (!isNaN(interval
) && interval
>= 0) {
94 reportInterval
= setInterval(reportLoop
, interval
);
99 * Add a callback to add additional metrics before reporting.
101 * @param {function(metricsReporter)} hook callback to be invoked before reporting
103 export function addReportHook(hook
) {
104 reportHooks
.push(hook
);
107 export function clearReportHooks() {
112 * Force metrics to be reported right now.
114 export function flush() {
118 function addDefaults() {
119 addProperty(MEM_RSS
, process
.memoryUsage().rss
/ 1048576);
120 addProperty(LOAD_1MIN
, os
.loadavg()[0]);
121 addProperty(TIMESTAMP
, new Date());
124 function reportLoop() {
125 if (delegate
!== null) {
128 reportHooks
.forEach(hook
=> {
133 logger
.error(error
.stack
);