NODEJS Contents

HTTP Logging Middleware (what to log)

Logging is your production memory: use structured logs with request IDs, latency, and error context to debug fast and measure reality.

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.