Examining Request Logging
I'm currently fleshing out the initial middleware structure. The core focus is on meticulous request logging within an Express.js context. I'm aiming to capture comprehensive request details, which will include specific data such as headers, query parameters, and, of course, the request body. My aim is to create a robust and configurable solution.
Calculating Server Metrics
I've been concentrating on calculating server metrics, especially latency and status codes. I'm moving beyond basic logging, incorporating Prometheus for metric exposure. I've chosen prom-client and will calculate metrics manually. My plan is to include a counter for total requests and a histogram for request duration to capture latency percentiles. I'm focusing on integrating these metrics within the Express.js framework to get them scraped by a Prometheus server.
Developing Middleware Structure
I'm now deep-diving into the actual code, focusing on the middleware. I've initialized the Prometheus registry and defined metrics as planned: a counter and a histogram. The middleware is taking shape; I'm capturing request start times and listening for response finishes. Next, I will calculate the duration, normalize paths to manage cardinality, and update the metrics accordingly. Finally, I'll need to expose all this data through the /metrics endpoint.
Optimizing Metric Accuracy
I'm currently focused on the specific implementation of the middleware and making it production-ready. I've realized req.route.path can help to reduce high cardinality in Prometheus, so that's been integrated. To be even more precise, I'm switching from Date.now() to process.hrtime() for timing. Also, I've confirmed that the middleware placement must be before any defined routes. My approach is to encapsulate everything into a separate, clean module.
Structuring Logging & Metrics
I'm now integrating detailed logging with the Prometheus setup. I've designed the imports, registry, and metrics with a http_request_duration_seconds histogram in mind. The Express middleware function is taking shape. I'm focusing on handling res.on('finish') to correctly log each request's final status. I need a robust strategy to handle route patterns to avoid high cardinality. The aim is to log in ms for ease of reading but track with the Prometheus standard.
Implementing JSON Logging
I'm now integrating JSON logging to enhance the Prometheus setup. Inside the res.on('finish') event, I'm constructing a JSON object that includes the traceId, HTTP method, URL, duration, user agent, and status code. This ensures detailed logging alongside Prometheus metrics. I'm focusing on the code's clarity and adding relevant comments, especially around the use of req.route to prevent cardinality issues. I've abandoned using response-time middleware to keep this native.
Crafting the Final Output
My current focus is crafting the final output, particularly how logs and metrics will be presented. I'm exploring different formatting options for the JSON log entries and ensuring they align seamlessly with the Prometheus metrics data. I'm also considering the best practices for presenting both in a combined way, potentially using a structured format that allows for easy analysis and visualization.
This guide provides a production-ready Express middleware solution. It uses prom-client for Prometheus integration and implements structured logging to capture request details.
Prerequisites
You will need to install the official Prometheus client for Node.js:
npm install express prom-client
The Implementation
Here is the complete code. I have structured it to handle High Cardinality, a common pitfall where dynamic URLs (like /users/123) flood Prometheus with too many unique keys.
Create a file named server.js:
const express = require('express');
const client = require('prom-client');
const app = express();
const PORT = 3000;
// --------------------------------------------------------
// 1. Prometheus Setup
// --------------------------------------------------------
// Create a Registry to hold metrics
const register = new client.Registry();
// Add default metrics (CPU, memory, event loop lag, etc.)
client.collectDefaultMetrics({ register });
// Define a custom Histogram metric for HTTP request duration.
// We use a histogram because it calculates p50, p90, and p99 percentiles.
const httpRequestDurationMicroseconds = new client.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status_code'],
buckets: [0.1, 0.5, 1, 2, 5], // Define buckets (0.1s, 0.5s, etc.)
});
register.registerMetric(httpRequestDurationMicroseconds);
// --------------------------------------------------------
// 2. The Middleware
// --------------------------------------------------------
const metricsMiddleware = (req, res, next) => {
// Start the timer
const start = process.hrtime();
// Listen for the response 'finish' event
res.on('finish', () => {
// Calculate duration in seconds
const diff = process.hrtime(start);
const durationInSeconds = (diff[0] * 1e9 + diff[1]) / 1e9;
const durationInMs = durationInSeconds * 1000;
// Resolve the route path to avoid high cardinality issues.
// If req.route exists, it means a route matched (e.g., "/users/:id").
// If not (404), we use req.path or a placeholder.
const routePath = req.route ? req.route.path : req.path;
const statusCode = res.statusCode;
// Update Prometheus Metric
httpRequestDurationMicroseconds
.labels(req.method, routePath, statusCode)
.observe(durationInSeconds);
// Detailed Logging (JSON format is best for aggregators like ELK/Datadog)
const logEntry = {
timestamp: new Date().toISOString(),
method: req.method,
route: routePath, // Use the template path, not the raw URL
url: req.originalUrl, // The actual raw URL
status: statusCode,
duration_ms: durationInMs.toFixed(2),
user_agent: req.get('User-Agent') || '',
ip: req.ip
};
// In production, use a library like 'winston' or 'pino'.
// For now, console.log suffices.
console.log(JSON.stringify(logEntry));
});
next();
};
// Apply middleware globally (must be before routes)
app.use(metricsMiddleware);
// --------------------------------------------------------
// 3. Routes
// --------------------------------------------------------
// The Metrics Endpoint (Prometheus scrapes this)
app.get('/metrics', async (req, res) => {
res.setHeader('Content-Type', register.contentType);
res.send(await register.metrics());
});
// Standard Route
app.get('/hello', (req, res) => {
// Simulate slight delay
setTimeout(() => {
res.json({ message: 'Hello World!' });
}, Math.random() * 200);
});
// Dynamic Route (Testing Cardinality)
app.get('/users/:id', (req, res) => {
const id = req.params.id;
res.json({ id, name: `User ${id}` });
});
// Error Route
app.get('/error', (req, res) => {
res.status(500).json({ error: 'Something went wrong' });
});
// --------------------------------------------------------
// Start Server
// --------------------------------------------------------
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Metrics exposed on http://localhost:${PORT}/metrics`);
});
Key Concepts Explained
1. High Cardinality Protection
This is the most critical part of the code snippet:
const routePath = req.route ? req.route.path : req.path;
If you have a route /users/:id and you log the raw URL (/users/1, /users/2), Prometheus will create a new time-series for every single user ID. This will consume all your memory and crash the scraper. By using req.route.path, we send /users/:id to Prometheus regardless of the actual ID passed.
2. process.hrtime()
We use High-Resolution Time instead of Date.now(). Not only is it more precise (nanoseconds), but it is also not affected by system clock drift (e.g., NTP updates).
3. res.on('finish')
We attach a listener to the response object. This ensures that we calculate the duration only after the response has historically been sent to the client.
How to Test
-
Run the server:
node server.js
-
Generate some traffic:
- Visit
http://localhost:3000/hello
- Visit
http://localhost:3000/users/123
- Visit
http://localhost:3000/users/456
- Visit
http://localhost:3000/error
-
Check the Logs:
Look at your terminal; you will see structured JSON logs showing the duration and normalized paths.
-
Check Prometheus Metrics:
Visit http://localhost:3000/metrics. You will see output similar to:
# HELP http_request_duration_seconds Duration of HTTP requests in seconds
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.1",method="GET",route="/users/:id",status_code="200"} 1
http_request_duration_seconds_sum{method="GET",route="/users/:id",status_code="200"} 0.0023
http_request_duration_seconds_count{method="GET",route="/users/:id",status_code="200"} 2
Notice that even though we visited user /123 and /456, Prometheus groups them under the single route /users/:id.