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.

JavascriptNodeResilience

Code

javascriptsnippet
39 lines
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);

How it works

Count the function handleCheckout as the entire surface area of Prom Client Counters and Histogram Metrics.

Await points sequence the asynchronous work; a rejection lands at the awaiting line.

Caveats

  • Plan for an install step: prom-client and express are a real dependency, resolved by the package manager.

Putting it to use

Entry signature: async function handleCheckout(req, res)

Core lines

app.get('/metrics', async (req, res) => {
res.set('content-type', registry.contentType);
res.end(await registry.metrics());
});

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `prom-client` and `express`. Without them the snippet will not load.