Prom Client Counters and Histogram Metrics
Instrument a service with prom-client counters for totals, histograms for latency buckets, and a default metrics endpoint for scraping.
Code
import promClient from 'prom-client';
import express from 'express';
const registry = new promClient.Registry();
promClient.collectDefaultMetrics({ register: registry, prefix: 'svc_' });
const ordersTotal = new promClient.Counter({
name: 'orders_created_total',
help: 'Total orders created',
labelNames: ['tenant', 'channel'],
registers: [registry],
});
const requestDuration = new promClient.Histogram({
name: 'http_request_duration_seconds',
help: 'Request latency distribution',
buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5],
labelNames: ['route', 'method'],
registers: [registry],
});
async function handleCheckout(req, res) {
const end = requestDuration.startTimer({ route: '/checkout', method: 'POST' });
try {
ordersTotal.inc({ tenant: 'acme', channel: 'web' });
res.json({ ok: true });
} finally {
end();
}
}
const app = express();
app.post('/checkout', handleCheckout);
app.get('/metrics', async (req, res) => {
res.set('content-type', registry.contentType);
res.end(await registry.metrics());
});
app.listen(3000);Report a problem with this exampleOpens a pre-filled issue on GitHub.