Creating logging middleware
The user wants me to create Express middleware that logs detailed request metrics and integrates with Prometheus, specifically using prom-client. I'll need to offer code samples that include a histogram for latency and counters for status codes.
Additionally, I’ll implement a /metrics endpoint with labels like method, path, status_code, and an error flag. I plan to compute the start time and log metrics upon finishing the response. I should also provide installation instructions for prom-client, along with optional suggestions for other logging libraries.Implementing metrics middleware
I’m working on a code snippet for metrics in Express using prom-client. The code sets up a registry and collects default metrics. I have a histogram to track request durations and counters to tally HTTP requests and errors.
For the middleware, I’ll track the start time using process.hrtime.bigint(). Since I can’t access the route right away, I plan to handle that in the res.on('finish') callback, using either req.route.path or req.originalUrl to ensure accurate logging.Completing the middleware setup
Inside the res.on('finish'), I’ll compute the request duration and record it in the histogram, then increment the request counter. I want to log key details, like the user agent and possibly the remote IP and content-length.
I also need to implement error detection, marking any responses with status codes of 500 or higher as errors. Although I initially considered a /metrics route, I’ll clarify how to integrate it as middleware instead and maintain clean logging practices. Additionally, I'll capture sanitized paths to avoid varying metrics cardinality, applying conventions for naming and setting the NODE_ENV variable.Crafting the middleware function
I’m planning to create a standalone middleware function called requestMetricsMiddleware({ logger, collectDefaultMetrics, prefix }). The user didn't ask for an extensive explanation, but I need to ensure the code covers detailed request metrics with comments for clarity.
I’ll use CommonJS syntax in the code snippet since that's still common in Node examples, but I'll indicate how to adjust if the user prefers ESM. My metrics file will include a registry from prom-client, histograms for request and response sizes, and counters. I’ll also note that measuring request size could involve using the content-length header, keeping in mind it’s not always accurate.Defining request metrics and middleware
I’m crafting the metrics and middleware for tracking detailed request metrics like method, path, status, and duration. Using prom-client, I'll set up histograms and counters with appropriate labels for monitoring.
The middleware function will compute request duration, log various details like content length and user agent, and store metrics upon the res.on('finish') event. I’ll make sure to avoid tracking the /metrics route to prevent unnecessary data.
Lastly, I'll provide guidance on installing required packages and mention edge cases without overwhelming the user with details. Here’s a complete example of an Express middleware that:
- Logs detailed per-request information (method, route, status, duration, sizes, user agent, IP).
- Exposes Prometheus metrics via
/metrics.
- Uses
prom-client with sane defaults and label choices.
1. Install dependencies
npm install express prom-client
2. Define Prometheus metrics
Create metrics.js:
// metrics.js
const client = require('prom-client');
// Create a registry so we can control what gets exposed
const register = new client.Registry();
// Collect default Node.js and process metrics (CPU, memory, event loop, etc.)
client.collectDefaultMetrics({ register });
// Histogram for request duration
const httpRequestDurationSeconds = new client.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status_code'],
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
registers: [register],
});
// Counter for total requests
const httpRequestsTotal = new client.Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
labelNames: ['method', 'route', 'status_code'],
registers: [register],
});
// Counter for 5xx errors
const httpRequestErrorsTotal = new client.Counter({
name: 'http_request_errors_total',
help: 'Total number of HTTP 5xx responses',
labelNames: ['method', 'route'],
registers: [register],
});
// Optional: histograms for request/response size (from Content-Length headers)
const httpRequestSizeBytes = new client.Histogram({
name: 'http_request_size_bytes',
help: 'Size of HTTP requests in bytes (from Content-Length)',
labelNames: ['method', 'route'],
buckets: [100, 1024, 10 * 1024, 100 * 1024, 1024 * 1024, 10 * 1024 * 1024],
registers: [register],
});
const httpResponseSizeBytes = new client.Histogram({
name: 'http_response_size_bytes',
help: 'Size of HTTP responses in bytes (from Content-Length)',
labelNames: ['method', 'route'],
buckets: [100, 1024, 10 * 1024, 100 * 1024, 1024 * 1024, 10 * 1024 * 1024],
registers: [register],
});
module.exports = {
register,
httpRequestDurationSeconds,
httpRequestsTotal,
httpRequestErrorsTotal,
httpRequestSizeBytes,
httpResponseSizeBytes,
};
3. Middleware implementation
Create requestMetricsMiddleware.js:
// requestMetricsMiddleware.js
const {
httpRequestDurationSeconds,
httpRequestsTotal,
httpRequestErrorsTotal,
httpRequestSizeBytes,
httpResponseSizeBytes,
} = require('./metrics');
// Helper to get a low-cardinality "route" label
function getRouteLabel(req) {
// Prefer Express route definition if available (e.g. "/users/:id")
if (req.route && req.route.path) {
const base = req.baseUrl || '';
return base + req.route.path;
}
// For 404s or middleware-only paths, fall back to path without query string
if (req.originalUrl) {
return req.originalUrl.split('?')[0];
}
return 'unknown_route';
}
function requestMetricsMiddleware(options = {}) {
const {
logger = console, // any logger with .info()
excludePaths = ['/metrics'], // paths to skip instrumentation
} = options;
return function metricsMiddleware(req, res, next) {
// Skip certain paths (like /metrics itself)
const path = req.path || req.originalUrl || '';
if (excludePaths.includes(path)) {
return next();
}
const startHrTime = process.hrtime.bigint();
// Capture request size from Content-Length header (if present)
const reqSizeHeader = req.headers['content-length'];
const requestSize = reqSizeHeader ? parseInt(reqSizeHeader, 10) : undefined;
// When the response is finished, record metrics and log
res.on('finish', () => {
const diffNs = process.hrtime.bigint() - startHrTime;
const durationSeconds = Number(diffNs) / 1e9;
const durationMs = durationSeconds * 1000;
const route = getRouteLabel(req);
const statusCode = res.statusCode;
const method = req.method;
const labels = {
method,
route,
status_code: String(statusCode),
};
// Response size from Content-Length header (if present)
const resSizeHeader = res.getHeader('content-length');
const responseSize = resSizeHeader ? parseInt(resSizeHeader, 10) : undefined;
// Prometheus metrics
httpRequestDurationSeconds.observe(labels, durationSeconds);
httpRequestsTotal.inc(labels);
if (statusCode >= 500) {
httpRequestErrorsTotal.inc({ method, route });
}
if (typeof requestSize === 'number' && !Number.isNaN(requestSize)) {
httpRequestSizeBytes.observe({ method, route }, requestSize);
}
if (typeof responseSize === 'number' && !Number.isNaN(responseSize)) {
httpResponseSizeBytes.observe({ method, route }, responseSize);
}
// Detailed structured log
const logPayload = {
timestamp: new Date().toISOString(),
ip: req.ip || req.connection?.remoteAddress,
userAgent: req.get('user-agent'),
http: {
method,
path: req.originalUrl,
route,
statusCode,
durationMs: Math.round(durationMs),
requestSizeBytes: requestSize,
responseSizeBytes: responseSize,
},
};
logger.info(logPayload);
});
next();
};
}
module.exports = requestMetricsMiddleware;
This middleware:
- Measures latency with
process.hrtime.bigint().
- Uses the Express route definition (
/users/:id) as the route label when available to avoid high-cardinality labels.
- Logs a structured JSON object you can send to any log system.
4. Wire it into your Express app
Create server.js:
const express = require('express');
const requestMetricsMiddleware = require('./requestMetricsMiddleware');
const { register } = require('./metrics');
const app = express();
// Parse JSON bodies, etc.
app.use(express.json());
// Apply metrics middleware early so it covers most routes
app.use(
requestMetricsMiddleware({
// You can plug in something like pino or winston here:
// logger: require('pino')(),
logger: console,
excludePaths: ['/metrics'], // do not record metrics for the metrics endpoint itself
})
);
// Example routes
app.get('/health', (req, res) => {
res.send({ status: 'ok' });
});
app.get('/users/:id', (req, res) => {
res.send({ id: req.params.id });
});
// Expose Prometheus metrics
app.get('/metrics', async (req, res) => {
try {
res.set('Content-Type', register.contentType);
const metrics = await register.metrics();
res.send(metrics);
} catch (err) {
res.status(500).send(err.message);
}
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
// Simple startup log
console.log(`Server listening on port ${port}`);
});
5. Scraping with Prometheus
In your Prometheus config:
scrape_configs:
- job_name: 'my-express-app'
static_configs:
- targets: ['my-service-host:3000'] # assuming /metrics is there
You now have:
- Detailed logs per request.
- Prometheus metrics for:
- Latency:
http_request_duration_seconds
- Request count:
http_requests_total
- Error count:
http_request_errors_total
- Request/response size:
http_request_size_bytes, http_response_size_bytes
If you want this in TypeScript or with a different logger (pino/winston), say so and I can adapt the code.