Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 43 ยท Errors and Robustness

Logging and Debugging

Log requests in Express with morgan and pino-http, write structured JSON logs, add correlation IDs, and debug internals with DEBUG=express:*.

When a server misbehaves in production you cannot attach a debugger and you cannot ask the user what they clicked. Logs are your memory of what happened. Good logging answers four questions fast: what was requested, what was answered, how long did it take, and if it failed, why?

This lesson covers the common logging tools for Express (morgan and pino-http), the idea of structured logs, correlation IDs that tie lines together across services, and the DEBUG environment variable that exposes Express's own internals. The real packages need npm, so they are read-only; the runnable examples build a small logger on the stand-in framework from Inside Express.

Two kinds of logs

What to log

Access logs One line per request: method, path, status, time.
Application logs Your own events: user created, payment failed.
Error logs Stack traces and the request they belong to.

Keep all three in the same format.

1 / 2

Access logs record every request and are usually produced by middleware. Application logs are lines your own code writes at interesting moments. Error logs come from your error handler (see Error Handling).

morgan: classic access logs

morgan is a small, long-standing middleware that writes one text line per request. It is read-only here:

JavaScript
import express from 'express';
import morgan from 'morgan';

const app = express();
app.use(morgan('dev')); // colored: GET /todos 200 4.2 ms - 83
// or, for servers:
// app.use(morgan('combined')); // Apache-style line with referrer and user agent

The format names dev, tiny, common and combined are built in, and you can write your own format string such as ':method :url :status :response-time ms'. Text lines are easy to read in a terminal but awkward for machines to search.

Structured logs and pino

A structured log is one JSON object per line instead of free text:

JSON
{"level":"info","time":"2026-03-01T10:15:00.000Z","reqId":"a1b2","method":"GET","path":"/todos","status":200,"ms":4}

Log tools (Loki, Elasticsearch, CloudWatch, Datadog and others) can filter such lines by field: "show all status >= 500 for reqId a1b2". pino is a very fast JSON logger and pino-http is its Express middleware. Read-only:

JavaScript
import express from 'express';
import pino from 'pino';
import pinoHttp from 'pino-http';

const logger = pino({
  level: process.env.LOG_LEVEL ?? 'info',
  redact: ['req.headers.authorization', 'req.headers.cookie'],
});

const app = express();
app.use(pinoHttp({ logger }));

app.get('/todos', (req, res) => {
  req.log.info({ count: 3 }, 'listing todos'); // request-scoped child logger
  res.json([]);
});

pino-http generates a request id, logs one line when each response finishes, and attaches req.log, a logger that automatically includes that id. The redact option removes sensitive paths before anything is written. In development people often pipe pino output through pino-pretty for readable colors.

Log levels

Levels let you turn detail up or down without changing code: fatal, error, warn, info, debug, trace. In production you usually run at info; when investigating a problem you temporarily lower the level to debug. Use error for failures that need attention, warn for odd but survivable situations, and info for normal business events.

A runnable stand-in logger

The following middleware does what pino-http does conceptually: it assigns a request id, measures the time, and writes one JSON line when the response finishes. To keep the output the same on every run, the clock and the id counter are injected: a fake clock advances 5 ms per reading and ids are numbered.

Node.js A structured access-log middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output in pairs: each request prints its own call result and the JSON log lines produced for it. The reqId in every line of one request is the same, and the level of the final line depends on the status code. The msg field and the extra fields (count, err) come from req.log, which is why a child logger per request is so useful: you never repeat the id by hand.

Time in the stand-in is fake on purpose. In real code use process.hrtime.bigint() or performance.now() for durations, and an ISO timestamp for time.

Correlation IDs across services

A single user action often touches several services: your Express API calls a payment service, which calls a bank gateway. When something fails, you need to find every log line from that one action. The trick is a correlation id (also called request id or trace id): create it at the edge, pass it along in a header (x-request-id is the common name), and include it in every log line.

sequenceDiagram
  participant C as Client
  participant A as API (Express)
  participant P as Payment service
  C->>A: POST /checkout
  Note over A: reqId = req-1
  A->>P: POST /charge<br/>x-request-id: req-1
  Note over P: logs with reqId req-1
  P-->>A: 201
  A-->>C: 201 + x-request-id: req-1

The same id appears in the logs of both services, so one search shows the whole story.

If the incoming request already has an x-request-id (set by a load balancer or an upstream service) you reuse it; otherwise you create one, as the middleware above does. The next example runs two servers: the checkout API calls a payment service and forwards the id.

Node.js One id across two services

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Group the log lines by reqId and you get one story per checkout: the checkout line, the payments lines, and the final answer. The third call shows an upstream id being preserved rather than replaced. In real systems this idea is standardized as the W3C traceparent header and OpenTelemetry, which Express apps can adopt later without changing the principle.

Debugging Express itself

Sometimes the question is not "what did the client send?" but "why did Express route this request that way?". Express and many of its dependencies use the debug package, which prints internal messages when the DEBUG environment variable names them. Read-only, run in your terminal:

Terminal
# everything Express logs about routing and middleware
DEBUG=express:* node server.js

# only the router
DEBUG=express:router node server.js

# on Windows PowerShell
$env:DEBUG = "express:*"; node server.js

You then see lines for every layer a request passes through, which is an excellent way to learn how middleware order really works. Do not leave DEBUG enabled in production; it is noisy and slows the server.

For stepping through code, start Node with the inspector (node --inspect server.js) and attach VS Code or Chrome DevTools. Breakpoints inside a handler let you inspect req and res directly.

Practical advice

  • Log one line per request, at the end, with status and duration. It is more useful than lines at the start.
  • Log to standard output and let the platform (Docker, systemd, your host) collect it. Do not manage log files inside the app.
  • Log errors once, in the central error handler, not at every layer.
  • Redact sensitive data such as authorization, cookie and password fields.
  • Choose levels deliberately so that production at info is readable.

The next lessons build on this: authentication appears in Sessions and Login, and Deployment covers where logs go in production.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of structured (JSON) logs over plain text lines?

    Fields like status and reqId can be queried directly by log tools, which is hard with free text.
  2. 2. What is a correlation id for?

    The same id in every service's logs lets you reconstruct one action end to end.
  3. 3. How do you see Express's internal routing messages?

    Express uses the debug package, which prints output for namespaces listed in the DEBUG environment variable.
  4. 4. Which of these should never appear in logs?

    Credentials in logs are a security leak. Redact them, for example with pino's redact option.

Summary

  • Log access lines, application events and errors in one consistent format.
  • morgan gives readable text lines; pino and pino-http give fast structured JSON with request-scoped loggers.
  • A correlation id, created at the edge and forwarded in x-request-id, ties logs from different services together.
  • DEBUG=express:* shows Express's own routing activity; never keep it on in production.
  • Log to stdout, log errors once, and redact secrets.

Next: Sessions and Login.