|
| 1 | +import client from 'prom-client'; |
| 2 | +import express from 'express'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Create a Registry to register the metrics |
| 6 | + */ |
| 7 | +const register = new client.Registry(); |
| 8 | + |
| 9 | +/** |
| 10 | + * Add default Node.js metrics (CPU, memory, event loop, etc.) |
| 11 | + */ |
| 12 | +client.collectDefaultMetrics({ register }); |
| 13 | + |
| 14 | +/** |
| 15 | + * HTTP request duration histogram |
| 16 | + * Tracks request duration by route, method, and status code |
| 17 | + */ |
| 18 | +const httpRequestDuration = new client.Histogram({ |
| 19 | + name: 'http_request_duration_seconds', |
| 20 | + help: 'Duration of HTTP requests in seconds', |
| 21 | + labelNames: ['method', 'route', 'status_code'], |
| 22 | + buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10], |
| 23 | + registers: [ register ], |
| 24 | +}); |
| 25 | + |
| 26 | +/** |
| 27 | + * HTTP request counter |
| 28 | + * Tracks count of HTTP requests by route, method, and status code |
| 29 | + */ |
| 30 | +const httpRequestCounter = new client.Counter({ |
| 31 | + name: 'http_requests_total', |
| 32 | + help: 'Total number of HTTP requests', |
| 33 | + labelNames: ['method', 'route', 'status_code'], |
| 34 | + registers: [ register ], |
| 35 | +}); |
| 36 | + |
| 37 | +/** |
| 38 | + * Express middleware to track HTTP metrics |
| 39 | + */ |
| 40 | +export function metricsMiddleware(req: express.Request, res: express.Response, next: express.NextFunction): void { |
| 41 | + const start = Date.now(); |
| 42 | + |
| 43 | + // Hook into response finish event to capture metrics |
| 44 | + res.on('finish', () => { |
| 45 | + const duration = (Date.now() - start) / 1000; // Convert to seconds |
| 46 | + const route = req.route ? req.route.path : req.path; |
| 47 | + const method = req.method; |
| 48 | + const statusCode = res.statusCode.toString(); |
| 49 | + |
| 50 | + // Record metrics |
| 51 | + httpRequestDuration.labels(method, route, statusCode).observe(duration); |
| 52 | + httpRequestCounter.labels(method, route, statusCode).inc(); |
| 53 | + }); |
| 54 | + |
| 55 | + next(); |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Create metrics server |
| 60 | + * @returns Express application serving metrics endpoint |
| 61 | + */ |
| 62 | +export function createMetricsServer(): express.Application { |
| 63 | + const metricsApp = express(); |
| 64 | + |
| 65 | + metricsApp.get('/metrics', async (req, res) => { |
| 66 | + res.setHeader('Content-Type', register.contentType); |
| 67 | + const metrics = await register.metrics(); |
| 68 | + |
| 69 | + res.send(metrics); |
| 70 | + }); |
| 71 | + |
| 72 | + return metricsApp; |
| 73 | +} |
0 commit comments