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?
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
- Write one JSON object per line to standard output. Let the platform collect it, as the Twelve-Factor guide advises.
- Use a stable event name (
payment.failed), not a sentence with values glued in. Put values in fields. - Use levels with meaning.
errormeans a human may need to act.warnmeans something degraded but worked.inforecords normal business events.debugis off in production. - 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.
- 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 withAuthorizationin 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?
Check yourself · 3 of 3
An agent adds log.info({ req }) to debug a login bug. What is the biggest risk?
Practice items, not counted towards your mastery.
Start here
- OpenTelemetry documentation (opens in a new tab)DocsFree
The vendor-neutral standard for traces, metrics and logs, with concepts and language guides.
- Monitoring Distributed Systems (Google SRE Book) (opens in a new tab)BookFree
Defines the four golden signals and explains why to page on symptoms and use percentiles.
- Alerting on SLOs (Google SRE Workbook) (opens in a new tab)BookFree
Worked burn-rate alerts that turn an SLO into pages that matter.
More for this topic
- Logging Cheat Sheet (OWASP) (opens in a new tab)ArticleFree
What to log, what never to log, and how to keep logs usable and safe.
- The Twelve-Factor App: Logs (opens in a new tab)ArticleFree
Treat logs as an event stream written to standard output, not files the app manages.