Structured Logging: JSON Logs, Correlation IDs, Aggregation
Structured logging with JSON output, correlation IDs, and log levels. Python structlog, Node.js pino, Java SLF4J, plus ELK and Loki aggregation stacks.
Introduction
Your production API is returning 500s intermittently. You SSH into a container, grep error across a log file, and get back hundreds of lines like this:
[2026-11-05 10:30:45] ERROR Order failed for user 12345, product 67890, amount $99.99
Which fields can you filter on? None — it’s one string. To find every request from that user you’d write a regex, hope the format never changed, and still miss the lines where a developer wrote “Order failed” differently. Now compare the same event as structured logging:
{"timestamp":"2026-11-05T10:30:45Z","level":"error","service":"order-service",
"message":"order_failed","user_id":12345,"product_id":67890,"amount":99.99,
"request_id":"abc-123","duration_ms":187}
Every field is queryable: level=error AND user_id=12345 finds this in milliseconds, across every service, without a regex in sight. That’s the difference between grepping text and querying data.
This guide covers the pattern end-to-end: emitting JSON logs in Python (structlog), Node.js (pino), and Java (SLF4J/Logback), propagating correlation IDs through a request, choosing between ELK and Loki for aggregation, and querying what you collected. If you want the pattern distilled to its context and forces first, see the structured logging pattern — this guide is the implementation walkthrough.
Why Structured Logging
Unstructured logs were designed for a human tailing a file. The moment you have more than one service, more than one replica, or any log volume at all, three things break down:
You can’t query what you can’t parse. A field embedded in a message string requires regex per format variation. Structured fields are indexed once and queryable forever — user_id:12345 works regardless of what the message says.
You can’t correlate a request across services. A request that touches the gateway, order service, payment service, and inventory produces four disconnected log entries. Add a request_id propagated through headers and all four become one story you can pull up by ID.
You can’t alert reliably. “Alert me when 5xx errors exceed 1%” is a one-liner against a level or status field. Against free text it’s a brittle substring match that breaks when someone rewords a message.
The cost is real though — JSON logs are bigger than text, indexing costs storage and CPU, and a badly designed field schema creates its own mess. Worth knowing before you commit.
When to Use — and When Not To
Structured logging earns its keep when you have volume, distribution, or automation needs. It doesn’t pay off everywhere.
| Use structured logging | Plain text is fine |
|---|---|
| Multiple services or replicas | Single CLI tool or script |
| Centralized aggregation (ELK, Loki, Datadog) | Logs read by a human, occasionally |
| Alerting on log conditions | Cron job that emails you on failure |
| Correlating requests across boundaries | Short-lived batch job |
| Compliance/audit querying requirements | Prototype you’ll throw away |
Don’t adopt it just because it’s the modern default. A side project with 50 requests a day gains almost nothing — grep still works at that scale. The tipping point is usually your second service or your first on-call incident you couldn’t diagnose from logs. If you’re already shipping to an aggregator, the extra JSON fields are nearly free. If you’re not shipping anywhere, fix that first — structured logs on a local disk nobody reads are just expensive text files.
How It Works: The Pipeline
A structured log travels through five stages. Understanding each one tells you where to invest effort.
The two stages teams under-invest in are middleware (without a request ID, correlation never happens downstream) and query (if nobody can search the logs, you paid storage costs for nothing).
Python: structlog
structlog wraps Python’s logging module and gives you a pipeline of “processors” — functions that transform each log event before it’s rendered. The pattern: enrich the event dict step by step, then serialize to JSON at the end.
Setup
# logging_config.py — structlog configuration
import logging
import sys
import structlog
def configure_logging(service_name: str = "order-service", env: str = "production"):
"""Configure structured logging. Call once at app startup."""
# Inject service/env into every event — this is the piece most
# setups forget. Without it, service_name is accepted and silently
# dropped, and every log line looks identical across services.
structlog.contextvars.bind_contextvars(service=service_name, env=env)
structlog.configure(
processors=[
structlog.contextvars.merge_contextvars,
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.CallsiteParameterAdder(
parameters=[
structlog.processors.CallsiteParameter.MODULE,
structlog.processors.CallsiteParameter.FUNC_NAME,
structlog.processors.CallsiteParameter.LINENO,
]
),
structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.stdlib.BoundLogger,
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True,
)
# Route stdlib log records (third-party libs, uvicorn) through the
# same JSON formatter so every line on stdout is parseable.
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
structlog.stdlib.ProcessorFormatter(
processor=structlog.processors.JSONRenderer(),
)
)
root_logger = logging.getLogger()
root_logger.handlers = [handler]
root_logger.setLevel(logging.INFO)
Three details worth noting. bind_contextvars at startup injects service and env into every log event — the previous version of this config accepted service_name/env parameters and never used them, so every service emitted identical-looking logs. merge_contextvars runs first so request-scoped values (bound later by middleware) merge into each event. And root_logger.handlers = [handler] replaces rather than appends — otherwise you get duplicate lines on every reconfiguration in tests.
Using the logger
# order_service.py — Structured logging in practice
import structlog
logger = structlog.get_logger()
class OrderService:
def create_order(self, user_id: int, items: list[dict]) -> dict:
logger.info(
"order_creation_started",
user_id=user_id,
items_count=len(items),
total_amount=sum(i["price"] * i["quantity"] for i in items),
)
try:
payment = self.payment_client.charge(
user_id=user_id,
amount=sum(i["price"] * i["quantity"] for i in items),
)
logger.info(
"payment_processed",
user_id=user_id,
payment_id=payment["id"],
amount=payment["amount"],
)
order = self.order_repo.create(
user_id=user_id, items=items, payment_id=payment["id"]
)
logger.info(
"order_created",
order_id=order["id"],
user_id=user_id,
total_amount=order["total"],
)
return order
except Exception:
# .exception() attaches the traceback automatically
logger.exception("order_creation_failed", user_id=user_id)
raise
The convention that makes this readable downstream: event names are snake_case nouns (order_created, payment_processed), never sentences. The sentence is rebuilt at query time; the field name is what you index on. Notice also that logger.exception inside an except block captures the traceback into an exception field — you don’t need to format it yourself.
Correlation IDs with contextvars
# middleware.py — Correlation ID middleware
import uuid
from typing import Optional
import structlog
from starlette.middleware.base import BaseHTTPMiddleware
def extract_user_id(authorization: Optional[str]) -> Optional[int]:
"""Pull user ID from a Bearer JWT. Returns None for anonymous requests."""
if not authorization or not authorization.startswith("Bearer "):
return None
try:
import base64
import json
payload = authorization.removeprefix("Bearer ").split(".")[1]
payload += "=" * (-len(payload) % 4) # base64 padding
return json.loads(base64.b64decode(payload)).get("sub")
except (ValueError, IndexError, KeyError):
return None
class CorrelationIdMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
# Clear leftover context from the previous request on this
# worker, then bind this request's values. Any log emitted
# downstream inherits these fields automatically.
structlog.contextvars.clear_contextvars()
bound = {"request_id": request_id}
if user_id := extract_user_id(request.headers.get("authorization")):
bound["user_id"] = user_id
structlog.contextvars.bind_contextvars(**bound)
response = await call_next(request)
response.headers["X-Request-ID"] = request_id
return response
# Every downstream log line now includes request_id and user_id:
# {"timestamp":"...","level":"info","request_id":"abc-123","user_id":456,...}
Two fixes versus the common version of this middleware: extract_user_id is now a real function (it was called but never defined), and user_id is only bound when a user actually exists — anonymous requests no longer emit "user_id": "" noise. clear_contextvars runs before binding, not after, because it wipes the structlog-bound context from a prior request on a reused worker; clearing after would erase what you just set.
If you’re propagating this through to downstream services, forward X-Request-ID on outgoing HTTP calls too — or better, emit a W3C traceparent header and let distributed tracing correlate everything, logs included.
Node.js: pino
pino is the fastest JSON logger in the Node ecosystem — it writes newline-delimited JSON directly, no string building in the hot path.
Setup
// logger.ts — pino structured logging
import pino from "pino";
import { AsyncLocalStorage } from "async_hooks";
// AsyncLocalStorage holds request-scoped values across async hops —
// the Node equivalent of Python's contextvars.
export const asyncLocalStorage = new AsyncLocalStorage<{
requestId: string;
userId?: string;
traceId?: string;
}>();
export const logger = pino({
level: process.env.LOG_LEVEL || "info",
formatters: {
level: (label) => ({ level: label }), // numeric level → "info"/"error"
},
mixin: () => {
// Runs on every log call — merges request context if it exists.
const store = asyncLocalStorage.getStore();
return store ? { ...store } : {};
},
timestamp: pino.stdTimeFunctions.isoTime,
redact: {
paths: ["password", "token", "authorization", "*.password"],
censor: "[REDACTED]",
},
});
The mixin function is the mechanism that makes correlation automatic — pino calls it on every log event and merges the result into the output object. Anything you stash in AsyncLocalStorage at request start rides along on every subsequent log line without being passed explicitly.
Middleware for correlation IDs
// middleware.ts — Correlation ID middleware for Express
import { randomUUID } from "crypto";
import type { NextFunction, Request, Response } from "express";
import { asyncLocalStorage, logger } from "./logger";
export function correlationIdMiddleware(
req: Request,
res: Response,
next: NextFunction,
) {
const requestId = (req.headers["x-request-id"] as string) || randomUUID();
const userId = req.user?.id;
res.setHeader("X-Request-ID", requestId);
const startedAt = Date.now();
asyncLocalStorage.run({ requestId, userId }, () => {
logger.info("request_started", {
method: req.method,
url: req.originalUrl,
});
res.on("finish", () => {
logger.info("request_completed", {
method: req.method,
url: req.originalUrl,
status: res.statusCode,
duration_ms: Date.now() - startedAt,
});
});
next();
});
}
AsyncLocalStorage.run establishes the context scope — everything inside the callback (the route handler, service calls, other middleware) sees requestId/userId via getStore(). Outside the callback the store is empty, so background jobs don’t accidentally inherit a dead request’s ID.
Child loggers
// service.ts — Child loggers with bound context
import { logger } from "./logger";
class OrderService {
private logger = logger.child({ service: "order-service" });
async createOrder(userId: string, items: OrderItem[]) {
this.logger.info({ userId, itemCount: items.length }, "order_creation_started");
const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
try {
const payment = await this.paymentService.charge(userId, total);
this.logger.info({ paymentId: payment.id, amount: payment.amount }, "payment_processed");
const order = await this.orderRepo.create({ userId, items, paymentId: payment.id });
this.logger.info({ orderId: order.id, userId, total }, "order_created");
return order;
} catch (error) {
this.logger.error({ err: error, userId, total }, "order_creation_failed");
throw error;
}
}
}
Two pino-specific details here. The signature is logger.info(fields, message) — fields first, message second — which is the reverse of most loggers and a common migration gotcha. And logger.child({ service: ... }) bakes the field into every line from that logger, which is how you get the service field per-component without bind_contextvars.
Java: SLF4J with Logback
Java’s answer is logstash-logback-encoder, an encoder that renders Logback events as JSON and merges MDC values in automatically.
Setup with Logback
<!-- logback.xml — JSON structured logging for Java -->
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<fieldNames>
<timestamp>@timestamp</timestamp>
<level>level</level>
<logger>logger</logger>
<message>message</message>
<thread>thread</thread>
</fieldNames>
<customFields>{"service":"order-service","env":"production"}</customFields>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
MDC for correlation IDs
// CorrelationIdFilter.java — MDC-based correlation IDs
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.UUID;
@Component
public class CorrelationIdFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String requestId = httpRequest.getHeader("X-Request-ID");
if (requestId == null || requestId.isEmpty()) {
requestId = UUID.randomUUID().toString();
}
MDC.put("request_id", requestId);
MDC.put("service", "order-service");
// MDC.put() rejects null values — only set user_id when present.
String userId = extractUserId(httpRequest);
if (userId != null) {
MDC.put("user_id", userId);
}
httpResponse.setHeader("X-Request-ID", requestId);
try {
chain.doFilter(request, response);
} finally {
MDC.clear(); // required — the worker thread gets reused
}
}
private String extractUserId(HttpServletRequest request) {
// Pull user ID from your auth context / JWT claim. Returns null
// for anonymous requests.
Object user = request.getSession(false) != null
? request.getSession(false).getAttribute("userId")
: null;
return user != null ? user.toString() : null;
}
}
Three things the naive version gets wrong. MDC.put("user_id", null) throws IllegalArgumentException on Logback — anonymous requests crash the filter, so null-check it. MDC.clear() in finally isn’t optional: servlet containers pool threads, and without clearing, the next request on this thread inherits your user_id and writes it into someone else’s logs — a subtle data leak. And extractUserId now exists instead of being an undefined call.
Emitting structured fields
// OrderService.java — StructuredArguments instead of string interpolation
import net.logstash.logback.argument.StructuredArguments;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import static net.logstash.logback.argument.StructuredArguments.kv;
@Service
public class OrderService {
private static final Logger logger = LoggerFactory.getLogger(OrderService.class);
public Order createOrder(Long userId, List<OrderItem> items) {
logger.info("order_creation_started",
kv("user_id", userId),
kv("items_count", items.size()));
try {
Payment payment = paymentService.charge(userId, calculateTotal(items));
logger.info("payment_processed",
kv("payment_id", payment.getId()),
kv("amount", payment.getAmount()));
Order order = orderRepository.save(new Order(userId, items, payment.getId()));
logger.info("order_created",
kv("order_id", order.getId()),
kv("user_id", userId),
kv("total", order.getTotal()));
return order;
} catch (PaymentException e) {
logger.error("payment_failed",
kv("user_id", userId),
kv("error", e.getMessage()),
e); // throwable last — Logback renders it as stack_trace
throw e;
}
}
}
This fixes the guide’s biggest self-contradiction: the old version told you to use “structured fields, not string interpolation” and then did exactly that with logger.info("order_created order_id={}"). kv() turns each argument into a real JSON field in the output ("order_id":123) instead of a substring inside message that nobody can index on.
Log Levels
Levels exist so that production stays readable at volume. The rule that keeps them honest: a log’s level should reflect how surprised you should be to see it, not how bad the thing is in absolute terms.
TRACE — Function entry/exit, variable dumps. Dev only.
DEBUG — SQL queries, cache hits, branch decisions. Staging and dev.
INFO — Business events: order created, user logged in. Production baseline.
WARN — Unexpected but handled: deprecated API hit, retry triggered.
ERROR — Something failed and needs a human: payment rejected, DB down.
FATAL — The process cannot continue. Rarely used; most apps exit via ERROR.
Two habits that prevent the usual level drift. First, expected failures aren’t errors — “user not found” on a login attempt is WARN at most, because it happens constantly and fixing it isn’t your job; reserving ERROR for things a human must act on keeps alert channels clean. Second, control level via environment (LOG_LEVEL=debug in staging) rather than code — you’ll need it the first time you have to debug a live issue without redeploying.
Designing Your Field Schema
JSON alone doesn’t make logs queryable — consistent field names do. If one service logs user_id, another userId, and a third uid, the query you actually wanted (user_id:12345) silently misses two thirds of your data. Teams discover this during an incident, which is the worst time to learn it.
Settle these rules early and write them down where every service can see them:
- snake_case everywhere.
user_id,order_id,duration_ms— never camelCase in one service and snake in another. JSON has no convention; your schema is the convention. - Units in the name.
duration_ms,size_bytes,timeout_seconds. A baredurationmeans different things in different languages and will bite you when a Java service logs milliseconds and a Python one logs seconds. - Flat over nested.
payment_idbeatspayment.id— nested fields are harder to index in Loki and more awkward to query in KQL. Keep the top level flat unless a nested group genuinely repeats (likehttp.status,http.methodif you adopt the OpenTelemetry conventions). - Reserve a core set and don’t improvise on it.
timestamp,level,service,env,message,request_id,user_id,trace_id,duration_ms,error. Anything else is a service-specific field — fine, as long as it follows the same rules. - One event, one name.
order_createdmeans the same thing everywhere. If the payment service calls the same eventpayment_completed, that’s a different event — name it differently on purpose, not accidentally.
A schema document with ten agreed fields is worth more than the most elegant logging setup. When in doubt, look at what OpenTelemetry’s semantic conventions already standardized — http.method, http.status_code, db.system, error.type — and reuse those names so your logs align with your traces later.
Sampling and Volume Control
The failure mode nobody budgets for: structured logging works so well that you start logging everything, and a month later your Elasticsearch bill tripled. Volume control is a design decision, not an afterthought.
Three levers, in order of preference:
- Log less at source. Not every endpoint deserves INFO. Health checks hit by a load balancer every five seconds generate 99% noise — drop them to DEBUG or skip them entirely in the middleware. The same applies to successful auth checks and cache hits on hot paths.
- Sample high-volume paths. If
/api/searchdoes 10k req/min, logging 1-in-100 requests at INFO (with asampled=truefield so queries know) keeps the signal and cuts the volume by two orders of magnitude. Always log errors unsampled — sampling is for the success case. - Bump verbosity dynamically. Level-by-environment gets you a static baseline; level-by-runtime-flag gets you a debug switch for incidents. Some teams expose
/admin/log-levelto turn a single service to DEBUG for ten minutes during an investigation, then it reverts automatically.
The guiding question for each field and each log call: will anyone query this in the next 90 days? If the answer is no, it doesn’t belong in production logs — it belongs in a metric, a trace span, or nowhere.
Choosing an Aggregation Stack
Emitting JSON is half the job — you still need somewhere to put it. The two self-hosted standards:
| ELK (Elasticsearch + Kibana) | Grafana Loki | |
|---|---|---|
| Indexes | Full document — every field | Labels only (service, level, env) |
| Query power | Full-text + field queries (KQL) | LogQL — good, more limited |
| Storage cost | High — inverted index on everything | Low — chunks compressed, index tiny |
| RAM footprint | Heavy — 1-2GB minimum per node | Light — runs happily on 512MB |
| Best for | Complex ad-hoc search, high QPS | Cost-efficient app logs at scale |
The decision usually comes down to how you search. If your debugging pattern is “find every mention of this user ID in the last hour,” Loki’s label model is fine and a fraction of the cost. If you’re doing forensic queries across arbitrary fields, Elasticsearch’s inverted index is worth the RAM. Many teams run both — Loki for app logs, Elasticsearch for audit trails that need deep search.
A third option worth mentioning: don’t self-host at all. Datadog, New Relic, and Grafana Cloud all ingest JSON logs natively, and for a team without a dedicated ops person the managed cost often beats the operational cost of running Elasticsearch well.
Querying Logs
Kibana (KQL)
# Find errors for a specific user
level:error AND user_id:12345
# Find logs for a request across services
request_id:"abc-123-def"
# Find slow database queries
message:"database_query" AND duration_ms:>1000
# Find errors in the last hour
level:error AND @timestamp:[now-1h TO now]
Grafana Loki (LogQL)
# All errors from the app in the last hour
{job="app"} | json | level="error"
# Follow one request across services
{job="app"} | json | request_id="abc-123"
# Error rate per service over 5-minute windows
sum(rate({job="app"} | json | level="error" [5m])) by (service)
The label-vs-field split matters here: in Loki you filter on labels ({job="app"}) first, then parse fields with | json. Putting service and level as labels (as the promtail config below does) makes those queries cheap; putting user_id as a label would be a mistake — labels go in the index, and high-cardinality labels (a unique value per user/request) blow up Loki’s index the same way they’d blow up Prometheus. Keep labels to low-cardinality dimensions; everything else stays a parsed field.
A Worked Example
One request, end to end, so the pieces connect. A POST /api/orders hits the gateway:
- Middleware generates
request_id: "f47ac10b", extractsuser_id: 456from the JWT, binds both to context. - OrderService logs
order_creation_started— automatically carriesrequest_id+user_id+service. - Payment call fails downstream; the service logs
payment_failedwitherrorandamountfields. - The same four fields appear in the payment service’s logs because the request ID was forwarded in
X-Request-ID.
Hours later, an alert fires on elevated 5xx. You open Grafana, run {job="app"} | json | level="error", see the payment_failed line, grab its request_id, run {job="app"} | json | request_id="f47ac10b", and get the complete story — every service, every step — in one ordered list. That’s the payoff the whole setup buys you: incident reconstruction in seconds, not a scavenger hunt through four SSH sessions.
Aggregation Setup
ELK Stack (Elasticsearch, Logstash, Kibana)
# docker-compose.yml — ELK stack
version: "3.8"
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:8.13.0
environment:
- discovery.type=single-node
- xpack.security.enabled=false
- ES_JAVA_OPTS=-Xms1g -Xmx1g
ports:
- "9200:9200"
volumes:
- es-data:/usr/share/elasticsearch/data
logstash:
image: docker.elastic.co/logstash/logstash:8.13.0
ports:
- "5044:5044"
volumes:
- ./logstash.conf:/usr/share/logstash/pipeline/logstash.conf
depends_on:
- elasticsearch
kibana:
image: docker.elastic.co/kibana/kibana:8.13.0
ports:
- "5601:5601"
environment:
- ELASTICSEARCH_HOSTS=http://elasticsearch:9200
depends_on:
- elasticsearch
volumes:
es-data:
# logstash.conf — Parse JSON logs from Filebeat
input {
beats {
port => 5044
}
}
filter {
json {
source => "message"
}
date {
match => ["timestamp", "ISO8601"]
}
}
output {
elasticsearch {
hosts => ["elasticsearch:9200"]
index => "app-logs-%{+YYYY.MM.dd}"
}
}
Grafana Loki
# docker-compose.yml — Loki + Grafana + Promtail
version: "3.8"
services:
loki:
image: grafana/loki:2.9.0
ports:
- "3100:3100"
command: -config.file=/etc/loki/local-config.yaml
promtail:
image: grafana/promtail:2.9.0
volumes:
- /var/log:/var/log
- ./promtail-config.yml:/etc/promtail/config.yml
command: -config.file=/etc/promtail/config.yml
grafana:
image: grafana/grafana:10.4.0
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
# promtail-config.yml — Scrape app logs and parse JSON
server:
http_listen_port: 9080
positions:
filename: /tmp/positions.yaml
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
- job_name: app-logs
static_configs:
- targets:
- localhost
labels:
job: app
__path__: /var/log/app/*.log
pipeline_stages:
- json:
expressions:
level: level
service: service
message: message
request_id: request_id
- labels:
level:
service:
# request_id is NOT a label — high cardinality would
# bloat the index. It stays a parsed field.
Note the deliberate omission in the label list — request_id is parsed but not labeled, per the cardinality rule above. A unique label value per request is exactly what Loki’s docs warn against.
Best Practices
- Log in JSON format — every line a parseable document, no exceptions for “quick” prints.
- Include a timestamp in ISO 8601 — don’t rely on collection time; buffering delays skew it.
- Propagate correlation IDs through
X-Request-IDheaders on both inbound and outbound calls. - Use consistent field names across services —
user_ideverywhere, notuserIdin one service anduidin another. Pick a schema and document it. - Name events as snake_case nouns (
order_created) and put variables in fields —logger.info("order_created", order_id=123), neverlogger.info(f"Order {id} created"). - Include
duration_mson anything with latency — DB queries, external API calls, queue waits. - Use async/non-blocking appenders in production so logging never stalls the request thread.
- Redact sensitive data at the logger level (
redact.pathsin pino, a processor in structlog) — filtering at query time is too late.
Common Mistakes
- Mixing formats: some services emit JSON, others plain text — aggregation breaks on the text ones. Standardize the output at the framework level so nobody can opt out accidentally.
- Missing correlation IDs: you can’t link logs from the same request. It’s the single highest-value field and the one teams skip first.
- Logging at the wrong level:
logger.error("User not found")for an expected condition burns out the alert channel. Expected failures are WARN or INFO. - Logging sensitive data: passwords, tokens, PII in plain text — a compliance incident waiting to happen. Redact at emission, not at query time.
- Excessive logging: every function call at INFO drowns the signal. DEBUG exists for that granularity; in production it stays off.
- No log rotation: unbounded local files fill disks and kill pods. Rotate locally, ship to the aggregator early.
- High-cardinality labels in Loki:
user_idorrequest_idas a label explodes the index. Labels are dimensions (service, level, env), fields are data.
See Also
- Structured logging pattern — the pattern itself: context, forces, and solution shape
- Logging, monitoring & observability guide — where logging fits in the three-pillar strategy
- Complete guide to distributed tracing — trace IDs, spans, and cross-service correlation
- Complete guide to Sentry error tracking — error aggregation as a complement to logs
- Runnable companion — the code from this guide as runnable examples
Further Reading
- structlog documentation — the Python reference for processors and contextvars
- pino documentation — Node.js JSON logger, including redaction and child loggers
- logstash-logback-encoder — the Java encoder for JSON output and StructuredArguments
- Grafana Loki documentation — label best practices and the cardinality rules this guide follows
Frequently Asked Questions
What is structured logging?
Logging where each entry is a machine-parseable document (typically JSON) with named fields instead of a free-text message. It makes logs queryable, filterable, and alertable the way application data is.
What is a correlation ID?
A unique identifier generated at request entry, propagated through every service call in headers, and stamped on every log line from that request. It's what turns four disconnected log entries across services into one traceable story.
ELK vs. Loki — which should I use?
Loki for cost-efficient app logs at scale — it indexes only labels, so storage is cheap and queries are good enough for most debugging. ELK for complex ad-hoc full-text search across all fields, at much higher RAM and storage cost. Many teams run Loki for app logs and keep Elasticsearch for audit trails.
How do I redact sensitive data in logs?
At the logger level. pino has redact.paths built in; structlog needs a processor that scrubs named fields; Logback uses pattern masking or a custom converter. Redacting at query time is too late — the data is already on disk and in backups.
What log level should I use in production?
INFO for business events, WARN for unexpected-but-handled conditions, ERROR for failures needing human action. Keep DEBUG/TRACE for staging and dev, and control levels via environment variables so you can turn verbosity up live when an incident demands it.
How do correlation IDs relate to distributed tracing?
They're the manual version of the same idea. A request_id in logs approximates what a trace_id gives you with distributed tracing — tracing adds spans, timing, and a proper UI. If you're propagating X-Request-ID headers already, adopting W3C traceparent is a small step up, and most tracing tools ingest trace IDs into logs automatically.
Related Resources
Structured Logging: Emit JSON Logs with Consistent Fields
How to emit structured JSON logs with consistent fields for searchability. Covers Python structlog, Winston, pino, Serilog, log levels, and log aggregation.
GuideDistributed Tracing: OpenTelemetry, Jaeger, Zipkin
Master distributed tracing with OpenTelemetry, Jaeger, and Zipkin. Trace propagation across services, span context, sampling strategies, and production debugging.
GuideLogging, Monitoring & Observability Guide
A guide to building observable systems with structured logging, metrics, and distributed tracing.
GuideSentry: Error Tracking, Triage, and Resolution
Master Sentry for production error tracking. Covers SDK integration in Python, Node.js, and Java, release tracking, source maps, performance monitoring, and alerting.
GuidePrometheus and Grafana: Metrics, Dashboards, Alerting
Instrument services with Prometheus metrics, query them in PromQL, build Grafana dashboards, and ship alerting rules that don't flap.
RecipeCentralize Container Logs with Fluentd and Docker
Collect, filter, and forward Docker container logs to Elasticsearch, S3, or stdout using Fluentd as a logging driver or sidecar.