librato-express
Version:
Middleware for expressjs to send metrics to Librato.
80 lines (65 loc) • 1.88 kB
JavaScript
var util = require('util');
const PREFIX_COUNT = 'count_';
const PREFIX_TIMER = 'timing_';
var Metrics;
module.exports = function (base) {
Metrics = base;
return {
Counter : Counter,
Timing : Timing
}
};
/* Common constructor routine. */
function MetricsController (opt, prefix) {
if (!Metrics.collector) {
throw new Error('librato-metrics module not initialized before use.');
}
if (!opt.name) {
throw 'Metrics options must have name';
}
var options = util._extend({}, opt);
options.source = options.source ? options.source : Metrics.source;
this.name = options.name = Metrics.prefix + prefix + options.name;
return options;
}
MetricsController.deleteMetrics = function (cb) {
Metrics.transport.deleteMetrics({names: [this.name + '*']}, cb);
};
/**
* Counter
* @param opt
* @constructor
*/
function Counter (opt) {
var modifiedOptions = MetricsController.call(this, opt, PREFIX_COUNT);
Metrics.collector.initCounter(modifiedOptions);
}
Counter.prototype.increment = function (step, filter) {
var self = this;
Metrics.queue.push(
function (cb) {
Metrics.collector.count(self.name, step || 1, filter, cb);
},
1
);
};
Counter.prototype.deleteMetrics = MetricsController.deleteMetrics;
/**
* Timer
* @param opt
* @constructor
*/
function Timing (opt) {
var modifiedOptions = MetricsController.call(this, opt, PREFIX_TIMER);
Metrics.collector.initTiming(modifiedOptions);
}
Timing.prototype.measure = function (time, filter) {
var self = this;
Metrics.queue.push(
function (cb) {
Metrics.collector.timing(self.name, (Date.now() - time), filter, cb)
},
1
);
};
Timing.prototype.deleteMetrics = MetricsController.deleteMetrics;