Skip to content

Instantly share code, notes, and snippets.

@colin-streicher
Created October 8, 2019 13:22
Show Gist options
  • Save colin-streicher/4a26758a2c47035435ce190f9839c416 to your computer and use it in GitHub Desktop.
Save colin-streicher/4a26758a2c47035435ce190f9839c416 to your computer and use it in GitHub Desktop.
Prometheus Metrics in NodeJS
const metrics = require("./metrics");
...
server.pre(metrics.startMetrics(server));
const prom = require('prom-client');
const restify = require("restify");
const prom_metrics = {}
prom_metrics.status = new prom.Counter({
name: 'status_codes',
help: 'Path Status Code',
labelNames: ['status_code']
});
prom_metrics.pathDuration = new prom.Histogram({
name: 'path_duration',
help: 'Duration for path',
labelNames: ['path', 'status_code', 'method']
});
prom_metrics.pathCount = new prom.Counter({
name: 'path_count',
help: 'Number of paths',
labelNames: ['path', 'status_code', 'method']
});
prom_metrics.pathDurationSummary = new prom.Summary({
name: 'path_duration_summary',
help: 'Summary of path durations',
labelNames: ['path', 'status_code', 'method']
});
prom.collectDefaultMetrics();
prom.register.setDefaultLabels({ service: ''});
function create(){
const server = restify.createServer({
name: 'Metrics'
});
server.get("/prom/metrics",function(req, res, next){
res.end(prom.register.metrics());
})
server.listen(8191, '0.0.0.0');
}
create();
function startMetrics(server){
return function(req, res, next){
server.on('after', restify.plugins.metrics({ server: server},
function(err, metric, req, res, route){
prom_metrics.pathDuration.observe({
path: metric.path,
status_code: metric.statusCode,
method: metric.method},metric.totalLatency);
prom_metrics.pathDurationSummary.observe({
path: metric.path,
status_code: metric.statusCode,
method: metric.method
}, metric.totalLatency);
prom_metrics.status.inc({status_code: metric.statusCode});
prom_metrics.pathCount.inc({
path: metric.path,
status_code: metric.statusCode,
method: metric.method
});
}));
next();
}
}
module.exports = exports = {
startMetrics: startMetrics
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment