How-To Guide

How to Implement Structured Logging

Log structured events: emit JSON with stable fields, bind context, choose levels deliberately, and query logs as data rather than text.

On this page

  1. Introduction
  2. Emit a JSON object with named fields
  3. Bind context once, carry it everywhere
  4. Choose levels with a consistent meaning
  5. Redact secrets at the logger
  6. Query the logs as data and test the fields
  7. Common pitfalls
  8. Conclusion

Introduction

A log line written as a formatted string is human-readable and machine-hostile: to find all the lines for one request, or count the errors of a type, a system must parse the text, and the format changes break the parse. A structured log line is an object with named fields, so the same questions are a filter on a field. Structured logging turns logs from text you read into data you query.

This tutorial covers emitting structured events, binding context to the logger, choosing levels with meaning, and querying the logs as data. The examples use a JSON logger, and the approach applies in any language with a structured logger.

Emit a JSON object with named fields

Each log line is a JSON object with a timestamp, a level, a message, and the fields relevant to the event. Instead of order 42 created for user 7, log { msg: 'order_created', orderId: 42, userId: 7 }. The named fields let a system filter on orderId or aggregate by the message, which the string cannot. The message becomes a stable event name, not a sentence that varies.

Keep the field names stable and documented, so a query written today works tomorrow. A field renamed from userId to user_id is a silent break for every saved query and dashboard. Treat the field names as a schema: adding a field is safe, renaming one is a breaking change that needs a migration.

import pino from 'pino';
const logger = pino();   // emits JSON by default

logger.info({ orderId: 42, userId: 7, total: 100 }, 'order_created');
// {"level":30,"time":...,"orderId":42,"userId":7,"total":100,"msg":"order_created"}

Bind context once, carry it everywhere

Attach the correlation id, the user, and the route to the logger once per request, so every line emitted during that request carries them without the code repeating them. A child logger bound with the context is the usual mechanism: create a logger with the request’s fields, and pass it into the code, so a log call only adds the event-specific fields.

The bound context is what makes a request’s logs findable: every line has the request id, so a query returns the whole story of one request across the services. Without it, correlating lines means matching on a timestamp and guessing. The binding is done once at the boundary, and the code below it never re-adds the context.

function middleware(req, res, next) {
  // bind once: every line for this request carries these fields
  req.log = logger.child({ requestId: req.id, route: req.route?.path, userId: req.user?.id });
  next();
}

// a handler logs event-specific fields only; the context is inherited
req.log.info({ itemCount: items.length }, 'cart_updated');

Choose levels with a consistent meaning

Define what each level means and use it the same way everywhere, so a filter on a level selects what you intend. A common definition: error for a failure that needs attention, warn for something recoverable or surprising, info for a notable state change, debug for detail used in development. The point is that the team agrees, so an alert on error does not fire for a benign warning logged as an error.

Log at the level the event deserves, not at the level that makes it visible. Over-logging at info floods the logs and the cost; under-logging at debug hides the detail when an incident needs it. Use the level filter to select, and make the levels meaningful so the filter is useful. A dynamic level that can be raised for a service under investigation is a good practice, so debug is available when needed.

// a consistent level policy
req.log.error({ err, orderId }, 'order_failed');     // needs attention
req.log.warn({ retryIn: 500 }, 'downstream_slow');   // recoverable, surprising
req.log.info({ orderId }, 'order_created');          // notable state change
req.log.debug({ payload }, 'request_body');          // detail for investigation

Redact secrets at the logger

A structured log is only safe if secrets do not enter it. Configure the logger to redact the known secret-bearing fields and headers, so a token or a password passed into a log call is dropped rather than serialized. A structured logger can redact by field path, which is more reliable than remembering not to log a secret at each call site.

Redact by key name for structured fields and by pattern for free text. Mark the fields that carry secrets, and test that a log call with a secret field emits a line without the value. This is the same redaction discipline as for secrets generally, applied at the logger so it is centralized.

const logger = pino({
  redact: { paths: ['req.headers.authorization', 'password', 'token'], remove: true },
});
logger.info({ password: 'hunter2', userId: 7 }, 'login');   // password is dropped

Query the logs as data and test the fields

Once the lines are structured, the queries are filters and aggregations on fields: all lines for a request id, the count of a message per hour, the slowest requests by a duration field. These are the questions structured logging answers quickly, and they are the ones asked during an incident. The logs become a queryable dataset, not a text file.

Test that a log line is valid JSON, that it carries the required fields, and that a secret field is redacted. A test that parses the logger’s output and asserts the fields catches a log line that is not structured or one that leaks a secret. The schema of the fields is a contract, and the test enforces it.

# query as data: all lines for one request, and the count of an event
jq -c 'select(.requestId == "abc")' app.log
jq -r 'select(.msg == "order_failed") | .err' app.log | sort | uniq -c | sort -rn

Common pitfalls

Logging a formatted string so the fields are not queryable, re-adding the context at every call instead of binding it once, using levels inconsistently so an alert fires on a warning, letting a secret enter a log line, and renaming a field so saved queries and dashboards break are the recurring mistakes. JSON lines with named fields, a bound context, a consistent level policy, logger redaction, and stable field names address them.

Conclusion

Structured logging turns logs into data. Emit JSON with named fields, bind the context once so every line carries the request id, choose levels with a consistent meaning, redact secrets at the logger, and query the fields. Self-check by asserting a log line parses, carries the expected fields, and drops a secret field. Then a log line answers a question with a filter instead of a regex.

Sources: OpenTelemetry: Logs data model, MDN: JSON, pino: JSON logger.

FAQ

Why log JSON instead of a formatted string?
A JSON line has named fields, so a log system can filter and aggregate on them, such as all lines for one request id or the count of a given error. A formatted string requires a regex to extract the same, which is fragile and slow.
What fields should every line carry?
A timestamp, a level, a message, and the correlation id at minimum, plus the service name. These are the fields you filter on most. Add domain fields such as the user, the route, and the outcome, so a line answers what happened without guessing.

Related Examples