Skip to content

Counters

Course: Prometheus and Grafana - chapter 5

Let’s add logic to count the number of requests (throughput) of our application.

  • Install prom-client
npm install prom-client
  • Create a new metrics/requestCount.ts file
import { NextFunction, Request, Response } from "express";
import client from "prom-client";
// Create a counter metric
const requestCounter = new client.Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
labelNames: ['method', 'route', 'status_code']
});
export const requestCountMiddleware = (req: Request, res: Response, next: NextFunction) => {
const startTime = Date.now();
res.on('finish', () => {
const endTime = Date.now();
console.log(`Request took ${endTime - startTime}ms`);
// Increment request counter
requestCounter.inc({
method: req.method,
route: req.route ? req.route.path : req.path,
status_code: res.statusCode
});
});
next();
};
  • Add the middleware to src/index.ts
  • Add a /metrics endpoint to src/index.ts
import client from "prom-client";
app.get("/metrics", async (req, res) => {
const metrics = await client.register.metrics();
res.set('Content-Type', client.register.contentType);
res.end(metrics);
})
  • Start the app
npm run start