HTTP Logging Middleware (what to log)
On this page
Why Logging Must Be Structured
Plain text logs do not scale in production. Structured logs (JSON) allow searching by requestId, status code, latency, and user identifiers while keeping privacy controls explicit.
Minimum Useful Fields
- timestamp
- requestId
- method, path
- status
- durationMs
- error code (if any)
Latency Measurement Middleware
import type { Request, Response, NextFunction } from 'express';
export function requestTiming(req: Request, res: Response, next: NextFunction) {
const start = process.hrtime.bigint();
res.on('finish', () => {
const end = process.hrtime.bigint();
const durationMs = Number(end - start) / 1e6;
void durationMs;
});
next();
}
Production Guidance
Do not log secrets, raw tokens, or full request bodies by default. Prefer allowlists and redaction. Logging should improve safety, not reduce it.