typescriptbeginner

Structured Request Logger Middleware

Express middleware that logs request/response details as structured JSON with timing information.

typescript
import { Request, Response, NextFunction } from 'express';

export function requestLogger(req: Request, res: Response, next: NextFunction) {
  const start = Date.now();

  res.on('finish', () => {
    const log = {
      timestamp: new Date().toISOString(),
      method: req.method,
      path: req.originalUrl,
      status: res.statusCode,
      duration: `${Date.now() - start}ms`,
      userAgent: req.headers['user-agent'],
      ip: req.ip,
    };
    console.log(JSON.stringify(log));
  });

  next();
}

Use Cases

  • API monitoring
  • Debugging and troubleshooting

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.