Skip to content
mentoor

Topic 1 of 5 · 4 min read

Structured logs with request context

Goal: Turn free-text log lines into structured events with a request id and no sensitive data.

A good log line is a structured event with a fixed name, a level, a request id and only the fields you need, so a machine can filter it and a person can follow one request through the system. Free text works until the first incident, then you are searching 2 million lines with grep.

Check yourself · 1 of 3

Which log line is best for finding one customer's failed payment later?

Choose one answer

Why it matters

A service written by an agent usually logs like a tutorial: console.log("error", err). That line has no user, no request, no order and no way to count it. When a customer says "my payment failed at 14:05", you need to find that one request among thousands. A request id makes that a one-line query.

How to do it

  1. Write one JSON object per line to standard output. Let the platform collect it, as the Twelve-Factor guide advises.
  2. Use a stable event name (payment.failed), not a sentence with values glued in. Put values in fields.
  3. Use levels with meaning. error means a human may need to act. warn means something degraded but worked. info records normal business events. debug is off in production.
  4. Attach context once. Create a request id (or reuse the incoming one) in middleware and add it, plus the trace id, to every line in that request. Most loggers have a child logger for this.
  5. Keep secrets and personal data out. Never log tokens, passwords, full card numbers, session cookies or prompts that contain customer text. Log ids, not content. The OWASP logging cheat sheet lists what to exclude.

Before and after

// Before
console.log("payment failed for " + user.email + " " + JSON.stringify(req.body));

// After
log.error(
  { event: "payment.failed", requestId, orderId: order.id, provider: "stripe", code: err.code },
  "payment provider rejected the charge",
);

The first line leaks an email and the whole request body, which may hold a card token. It also cannot be counted. The second produces one JSON line you can filter by event and requestId, and it holds nothing sensitive.

What goes wrong

  • Logging whole objects. log.info(req) dumps headers with Authorization in them.
  • No request id. Lines from 50 concurrent requests interleave and cannot be separated.
  • Everything at error. A missing optional field then pages someone at night, and real errors drown.
  • Unbounded volume. A debug line inside a loop can produce millions of lines and a large bill.

Examples

Child logger per request

app.use((req, res, next) => {
  const requestId = req.header("x-request-id") ?? crypto.randomUUID();
  req.log = logger.child({ requestId });
  res.setHeader("x-request-id", requestId);
  next();
});

Every req.log.info(...) now carries requestId. Returning the id in a response header lets support ask a customer for it.

Redacting by default

const logger = pino({
  redact: ["req.headers.authorization", "req.headers.cookie", "*.password", "*.token"],
});

Redaction paths are a safety net, not a licence to log whole objects. Choose fields on purpose, and keep the net for mistakes.

Key points

  • Write one JSON object per line with a stable event name and values in fields, not glued into a sentence.
  • Add a request id and trace id once, in middleware, so every line in a request carries them.
  • Reserve error for events where a human may need to act; use warn and info for the rest.
  • Log ids, not content: never tokens, passwords, card data, cookies or raw customer text.
  • Logging whole request or response objects is the most common way secrets reach the logs.

Common mistakes

  • Concatenating values into the message string, which makes the line impossible to filter or count.
  • Logging request bodies or prompts to help debugging, then keeping them for 90 days.
  • Using error for expected outcomes such as a failed login, which hides real faults.
  • Adding the request id to some lines by hand instead of once in middleware.

Check yourself · 2 of 3

What is the main job of a request id in logs?

Choose one answer

Check yourself · 3 of 3

An agent adds log.info({ req }) to debug a login bug. What is the biggest risk?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic