Structured Logging Best Practices: JSON Logs, Correlation IDs and Log Levels

Make logs useful in production: structured JSON logging, consistent fields, correlation and trace IDs, log levels, redacting secrets, and centralised search.

Published December 4, 2026

Plain text logs like "Error processing order" are nearly useless at scale. Which order? Which user? Which request? Which server? Structured logs record events as key-value data, usually JSON, so you can filter, aggregate and correlate them across thousands of instances in seconds. Small conventions make a huge difference during incidents.

The concept

A structured log event has a timestamp, level, message and fields: service, environment, request_id, trace_id, user or tenant ID (where allowed), and event-specific data such as order_id and amount. Log aggregation systems (Elasticsearch/OpenSearch, Loki, cloud logging services) index these fields so you can query "all errors for order 123 across every service in the last hour".

Correlation is the superpower. Generate or accept a request ID at the edge, pass it through every service call and queue message, and include it, plus the OpenTelemetry trace ID, in every log line. Then a single ID connects logs, traces and user reports. Equally important: never log secrets, tokens or full payment details, and be deliberate about personal data.

Unstructured vs structured

UnstructuredStructured
"Payment failed for user 42"{"level":"error","msg":"payment failed","user_id":42,"order_id":"A123","provider":"razorpay","error_code":"card_declined","trace_id":"4bf9…"}
Hard to filter by fieldQuery: error_code="card_declined" AND provider="razorpay"
Regex parsing breaks on format changesFields are explicit and typed

Log levels

LevelUse forAlert?
DEBUGDetailed diagnostics, off in production by defaultNo
INFONormal significant events (order placed, job finished)No
WARNUnexpected but handled (retry succeeded, fallback used)Trend only
ERROROperation failed and needs attentionPossibly, via rate
FATALProcess cannot continueYes

Correlation IDs

headermetadataconsumeEdgeassign request_idAPIlog + propagateQueue messagecarries idWorkersame id in logs
One ID follows the request everywhere.

Practical examples

Structured logging in Node.js with pino

Fast JSON logging with child loggers for context.

import pino from 'pino'
const logger = pino({ redact: ['req.headers.authorization', 'card.number'] })

app.use((req, res, next) => {
  req.log = logger.child({ request_id: req.get('x-request-id') ?? crypto.randomUUID() })
  next()
})
req.log.info({ order_id: 'A123', total_paise: 249900 }, 'order placed')

Python structlog

Bind context once, include it in every event.

import structlog
log = structlog.get_logger().bind(service="orders", env="prod")
log = log.bind(request_id=request_id, trace_id=trace_id)
log.error("payment_failed", order_id="A123", error_code="card_declined")

Query logs in Loki (LogQL)

Filter by labels, then by JSON fields.

{service="orders", env="prod"} | json | level="error" | error_code="card_declined"

Common mistakes

  • Logging secrets, tokens or full card numbers.
  • Inconsistent field names across services (userId, user_id, uid).
  • Logging everything at INFO and drowning in noise and cost.
  • No request or trace ID, making cross-service debugging guesswork.

Key takeaways

  • Log events as structured key-value data, usually JSON.
  • Standardise field names and include request and trace IDs.
  • Use levels deliberately and keep DEBUG off in production.
  • Redact secrets and personal data at the logger.

FAQ

Are logs or metrics better for alerting?

Metrics are cheaper and more reliable for alerting; logs are for investigating why.

How do I control logging costs?

Sample noisy INFO logs, drop health-check logs, shorten retention for verbose data and keep ERROR logs longer.

Should I log request and response bodies?

Rarely, and only with redaction; they often contain personal data and secrets.

More DevOps articles