Skip to the page

Structure, logging, testing and shutdown · mid

Structured logging and request IDs

Production logs should be structured JSON lines with a level, a timestamp, a request ID and useful fields, written to stdout and collected by the platform, and they must never contain passwords, tokens or other secrets.

The notes

What you must know

  • Use a structured logger (pino is the fast default for Node; v10 current) instead of console.log: fields can be searched, filtered and graphed.
  • Levels: fatal, error, warn, info, debug, trace. info in production, debug locally; make it configurable.
  • Request logging middleware (pino-http) logs method, URL, status and duration and gives each request an id. Return it in a response header (e.g. X-Request-Id) so users can quote it in bug reports.
  • Correlate across services: forward the request id (or the W3C traceparent header) and include it in every log line (child loggers or AsyncLocalStorage).
  • Redact secrets and personal data: Authorization headers, cookies, passwords, OTPs, card numbers, full Aadhaar or PAN numbers.
  • Log to stdout and let Docker, Kubernetes or CloudWatch ship the logs. Very chatty logging costs CPU on the one JS thread.

The red pen

Common traps: mistake → fix

  • Mistake: console.log is fine in production

    Fix: unstructured text has no levels, no fields and no redaction.

  • Mistake: Log the whole request body to debug faster

    Fix: bodies contain passwords, tokens and personal data.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you log in a Node API in production?
  2. How do you find all logs for one failing request across three services?
  3. What must never be logged?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview