Observability and SREVol. 9 · Part IX
0 / 0

Shelves / Observability and SRE

OB·99

Logging

Logging done well: structured logs and why plain text fails at scale, what to log and what not to, log levels and their contracts, correlation, request and trace IDs, canonical log lines, sensitive data handling (PII, secrets, redaction, regulation), logging performance, aggregation pipelines (agents, Collector, Fluent Bit, Vector) and storage choices (Loki, Elasticsearch/OpenSearch, ClickHouse, cloud logging), querying, retention and cost, with idiomatic structured logging in Java, Go, Python, Rust, Node and C++.

27 topics · ~20 min read · 30-question quiz
Updated Suggest a correction

Start here: logs a machine can read

A log line is an event with fields

A log is a timestamped record that something happened. Compare two lines describing the same request:

Text
2026-10-30 09:29:56 INFO orders request /order biryani 200 909.6ms
{"ts": "2026-10-30T09:29:56", "service": "orders", "level": "INFO", "msg": "request", "route": "/order",
 "dish": "biryani", "status": 200, "duration_ms": 909.6, "trace_id": "df2a2fa8cc9944a181a6593adac0f2d7"}

The first is shorter (65 bytes against 148 in the lab) and easy for a person to read. The second is a structured log: every value has a name, so a log system can answer "how many biryani orders took over 500 ms?" or "show me this request's trace" without guessing what the fourth word means. The extra bytes compress away (chapter 97 measured gzip at 8.6×), and the cost of writing it was 14.6 µs against 12.0 µs per line.

Levels say how much a line matters

Level Use for In production
DEBUG Details useful while developing or chasing a bug Off (or on for one service, briefly)
INFO Normal significant events: request finished, order state changed On
WARN Something unexpected that was handled: retry, fallback, slow dependency On
ERROR An operation failed and someone may need to act On, often alerting via metrics

Turning DEBUG off only saves work if the message isn't built first. In the lab, a disabled log.debug(f"cart contents {cart}") still cost 85.6 µs per call because Python builds the f-string before calling debug; log.debug("cart contents %s", cart) cost 0.23 µs because formatting happens only if the level is enabled.

Three rules that prevent most logging pain

  1. Constant message, variable fields: msg="payment failed", reason="card_expired", not "payment failed for order 9817 because the card expired". Constant messages group and count cleanly.
  2. Always include the trace ID (and request or user IDs where allowed), so one request's lines can be found across services.
  3. Never log secrets or personal data you aren't allowed to keep: passwords, tokens, card numbers, full request bodies. Logs are copied widely and kept for months.

How deep to go in logging

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain structured logs, levels and why trace IDs belong in log lines
L2 Write structured, correlated, secret-free logs with a logging library
L3 Design canonical log lines, redaction, sampling, collection and retention
L4 Diagnose lost, garbled, duplicated or expensive logs in a pipeline
L5 Design an organisation's logging standard, pipeline and cost model
L6 Run logging as a platform with governance, audit trails and compliance

Structured logs

Why plain text fails

A classic log line:

Text
2026-10-24 14:05:17 ERROR Payment failed for order 9817 (user 42): card expired after 3 attempts

is readable by a person and hostile to machines: to count failures by reason, filter by user or join with traces, you write fragile regular expressions, which break when someone rephrases the message.

A structured log is a record of named fields, usually serialised as JSON (one object per line) or logfmt:

JSON
{"timestamp":"2026-10-24T08:35:17.412Z","level":"ERROR","service.name":"payments",
 "service.version":"1.4.2","message":"payment failed","event":"payment.failed",
 "order.id":"9817","user.id":"42","payment.reason":"card_expired","attempts":3,
 "trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7",
 "http.route":"/payments","duration_ms":182}

Now any field can be filtered, grouped and aggregated (count by payment.reason where service.name = payments), logs join with traces by trace_id, and the human-readable message stays as one field.

Principles:

  • Constant message, variable fields: "payment failed" plus fields, not "payment failed for order 9817". Constant messages group cleanly and make log-based metrics and alerts trivial.
  • Consistent field names across services (follow OpenTelemetry semantic conventions where they exist: service.name, http.request.method, http.response.status_code, exception.type, user.id).
  • UTC timestamps in ISO 8601 / RFC 3339 with milliseconds or better.
  • One event per line: multi-line stack traces belong inside a field (exception.stacktrace), not as separate lines that collectors must reassemble.
  • Log to stdout/stderr in containers and let the platform collect (twelve-factor); don't manage files and rotation inside the app.

What to log

Log events that matter for understanding behaviour:

  • Request/operation outcomes at service boundaries (often one canonical log line per request, below).
  • State changes and decisions: order state transitions, circuit breaker opened, retry exhausted, fallback used, feature flag evaluated to an unusual value.
  • Errors and warnings with context and stack traces.
  • Lifecycle: startup with configuration summary (without secrets), shutdown, migrations, cache warm-up.
  • Security-relevant events: authentication success/failure, permission denials, admin actions (often to a separate audit log with stricter retention and integrity).

Don't log: every loop iteration, successful health checks, full request/response bodies by default, secrets, or data you aren't allowed to keep.

Canonical log lines

Canonical log lines (popularised by Stripe) emit one rich, structured line per request per service at the end of the request, containing everything important: route, status, duration, user/tenant, sizes, counts of DB queries and cache hits, feature flags, rate-limit state, error class, trace ID. They make most questions answerable with a single query over a single event type, and they're the logging face of the wide events idea (chapter 97).

Python
# Python (structlog): accumulate context during the request, emit one canonical line at the end
import time, structlog
log = structlog.get_logger()

async def canonical_log_middleware(request, call_next):
    structlog.contextvars.clear_contextvars()
    structlog.contextvars.bind_contextvars(http_route=request.scope.get("route_path"),
                                           http_method=request.method, request_id=request.headers.get("x-request-id"))
    start = time.perf_counter()
    status = 500
    try:
        response = await call_next(request)
        status = response.status_code
        return response
    finally:
        log.info("request.completed", http_status_code=status,
                 duration_ms=round((time.perf_counter() - start) * 1000, 1))   # plus anything handlers bound

Log levels

Levels let you filter by importance and control volume. Their meaning must be agreed, or they're useless:

Level Contract Example Alerting
FATAL / CRITICAL Process can't continue; about to exit Can't bind port, corrupted config Process crash alerts already cover it
ERROR An operation failed and someone may need to act; the system couldn't handle it Payment provider returned an unexpected 500 after retries; data inconsistency detected Not per line: alert on rates via metrics/SLOs
WARN Something unexpected, handled, that might indicate a problem if it continues Retry succeeded on 3rd attempt; fallback to cached prices; deprecated API used Watch trends
INFO Normal, significant business or lifecycle events Order placed; service started; canonical request line No
DEBUG Detailed diagnostic information for developers Computed discount components; cache key details Off in production by default
TRACE Extremely verbose, step by step Every message parsed Off

Practical rules:

  • Expected client errors are not ERRORs: a user typing a wrong password or requesting a missing resource is INFO or WARN (or just a metric). Reserve ERROR for failures of your system, otherwise ERROR becomes noise.
  • Log an error once, where it's handled, not at every layer it passes through ("log and rethrow" produces the same stack trace five times).
  • Dynamic levels: change the level at runtime per logger or per request (Spring Boot actuator loggers endpoint, slog.LevelVar in Go, log level via config reload), and enable debug logging for one tenant or request using baggage or a header, rather than for everyone.

Correlation

Request IDs, correlation IDs, trace IDs

Identifier Scope Purpose
Request ID One inbound request to one service (often generated at the edge: X-Request-ID) Find all logs for one request; returned to clients for support tickets
Correlation ID One business operation across many services and asynchronous steps (order placement → payment → shipping, possibly over hours) Follow a workflow end to end, including through queues and batch jobs
Trace ID One distributed trace (W3C traceparent) Join logs with traces and spans automatically
Span ID One operation within a trace Pinpoint which step emitted the log

Modern practice: let OpenTelemetry trace context carry the trace ID through HTTP, gRPC and messaging, and inject trace_id/span_id into every log record automatically via logging integrations (MDC in Java, slog handlers in Go, logging instrumentation in Python, tracing spans in Rust). Keep a separate business correlation ID (or use span links and baggage) for long-running workflows that span many traces.

Return the request or trace ID in an error response header or body ("error_id": "4bf92f35…") so support teams can find the exact logs and trace for a user's complaint.

client gatewayreq r-77 ordersspan a1 paymentsspan b2 trace 4bf9… (traceparent header) Kafka shippingnew trace correlation_id = order-9817travels in message headers log store: trace_id = 4bf9… OR correlation_id = order-9817→ every line from gateway, orders, payments and shipping, in order
Correlation through a request. The edge assigns a request ID and starts a trace; every service's log lines include the same trace ID (and their own span ID), and a business correlation ID travels with the order through asynchronous messaging, so one query reconstructs the whole story.

Structured logging across languages

// Java: SLF4J 2 fluent API with Logback + JSON encoder; trace IDs added to MDC by the OTel agent
private static final Logger log = LoggerFactory.getLogger(PaymentService.class);

log.atWarn()
   .setMessage("payment retry succeeded")
   .addKeyValue("order.id", order.id())
   .addKeyValue("payment.attempts", attempts)
   .addKeyValue("payment.provider", provider)
   .log();
// Spring Boot 3.4+: structured logging built in, e.g. logging.structured.format.console=ecs (or logstash, gelf)

Sensitive data

What must not be logged

Logs are copied widely (agents, pipelines, backends, exports, backups) and read by many people, so treat them as less protected than your database:

  • Secrets: passwords, API keys, tokens (Authorization headers, session cookies, JWTs), private keys, connection strings with credentials.
  • Payment data: full card numbers (PCI DSS forbids storing the full PAN unprotected and forbids storing CVV at all), bank account numbers.
  • Personal data (PII) beyond what's necessary: names, emails, phone numbers, addresses, government IDs, precise location, health data, IP addresses (personal data under GDPR in many contexts).
  • Request and response bodies by default (they contain all of the above).

Regulations matter: GDPR (data minimisation, purpose limitation, right to erasure, which is hard to honour in immutable log stores), India's DPDP Act, HIPAA, PCI DSS. Personal data in logs extends the scope of these obligations to your whole logging pipeline.

Techniques

  • Allow-list logging: log specific, chosen fields, never whole objects (log.info("user", user) dumps everything, including the password hash someone added last year).
  • Typed wrappers that redact on toString (Secret<String> in Rust's secrecy crate, Java records overriding toString, Pydantic SecretStr).
  • Redaction in the logger (pino redact, Logback masking patterns, structlog processors) and again in the pipeline (OpenTelemetry Collector redaction/transform processors, Fluent Bit filters) as a safety net.
  • Pseudonymise identifiers when you need correlation but not identity (hash user IDs with a keyed HMAC; tokenise).
  • Scan logs for leaked secrets and PII (DLP tools, cloud services like Macie, Purview, Sensitive Data Protection).
  • Access control and audit on the log platform; separate highly sensitive audit logs.

Performance

Logging has costs inside the application too:

  • Formatting and serialisation cost CPU even when the line is discarded; use parameterised/lazy APIs (log.debug("x={}", x), slog attributes, tracing macros that check the level first) and guard expensive computations (if log.isDebugEnabled()).
  • Synchronous I/O to stdout or files can block request threads when the consumer is slow; use asynchronous appenders with bounded queues (Logback AsyncAppender, Log4j 2 async loggers with LMAX Disruptor), and decide whether to drop or block when full.
  • Volume: high-throughput services can produce gigabytes per hour; sample repetitive logs (log 1 in 100, or rate-limit identical messages), and prefer metrics for counting.
  • Allocations: zero-allocation loggers (zerolog, zap in Go; quill in C++) matter on hot paths.

Aggregation and storage

Collection

podsJSON → stdout node files/var/log/pods agentparse · enrichredact · sample Kafka storeLokiOpenSearchClickHouse object storage archivecheap, long retention queries · dashboards · alertsLogQL · KQL · SQL · Lucene
A log pipeline. Applications write structured logs to stdout; the container runtime stores them on the node; an agent (Fluent Bit, Vector, OTel Collector filelog receiver) tails the files, parses and enriches them with Kubernetes metadata, redacts and filters, then ships them to storage, often via a buffer such as Kafka for large volumes; queries and alerts run on the store.
  • Agents: Fluent Bit (C, lightweight, CNCF), Vector (Rust, Datadog-maintained, transforms in VRL), the OpenTelemetry Collector (filelog receiver, OTLP logs), Promtail's successor Grafana Alloy, Fluentd (Ruby, older), Logstash (Elastic), cloud agents (CloudWatch agent, Azure Monitor Agent, Ops Agent).
  • Direct OTLP logs from the SDK skip file tailing entirely, carrying trace context and resource attributes natively.
  • Buffering: Kafka or Kinesis in front of storage absorbs bursts and decouples ingestion from indexing.

Storage backends

Backend Model Strengths Trade-offs
Grafana Loki Indexes only labels (service, namespace, level); log content stored compressed in object storage; content searched by brute-force filtering at query time Cheap at scale, simple ops, LogQL similar to PromQL, native OTLP Keep label cardinality low; full-text search over wide time ranges is slower
Elasticsearch / OpenSearch Full-text inverted index on fields and content Fast arbitrary search, rich aggregations, Kibana/OpenSearch Dashboards, SIEM use Indexing is CPU-, memory- and storage-heavy; costly at high volume
ClickHouse (and products built on it: SigNoz, HyperDX/ClickStack, Uptrace) Columnar analytics database Fast aggregations over huge volumes, good compression, SQL Schema design and operations expertise
Cloud services CloudWatch Logs (Logs Insights), Azure Monitor Logs (Log Analytics, KQL), Google Cloud Logging (with Log Analytics/BigQuery) Zero ops, integrated Ingestion pricing; vendor-specific query languages
Commercial Splunk, Datadog Logs, Elastic Cloud, Sumo Logic, New Relic Powerful search and analytics, security use cases Cost at volume
Text
# LogQL (Loki): error rate per route over 5 minutes from structured JSON logs
sum by (http_route) (
  rate({service_name="payments", level="ERROR"} | json | payment_reason != "" [5m])
)

# LogQL: find the slow requests' lines for one trace
{service_name=~"orders|payments"} | json | trace_id = "4bf92f3577b34da6a3ce929d0e0e4736"

Retention and cost

Different logs have different value over time; manage them in tiers:

Log type Hot (searchable, fast) Warm/cold Notes
Debug/trace logs Off in prod, or hours — Enable temporarily, scoped
Application INFO/WARN/ERROR 7–30 days Archive 30–90 days Most investigations are within days
Canonical request logs 14–30 days Months, for analytics Or derive metrics and drop
Audit and security logs 90 days–1 year Years (regulatory: often 1–7 years), immutable Tamper-evident storage (object lock), restricted access
Access logs (load balancers, CDN) Days Archive for security/forensics Large volume

Cost levers: drop at the source (don't emit noise), filter and sample in the pipeline (keep all errors, sample successful-request INFO lines), derive metrics from logs and keep only the metric, shorter hot retention with cheap archives (S3/GCS with Glacier-class lifecycle), and per-team budgets with visibility. Also honour deletion obligations: retention limits are a privacy control, not just a cost one.

Log-based alerting

Alert on rates and patterns, not individual lines: "ERROR rate for payments > 1% for 5 minutes", "any event=data.integrity_violation", "authentication failures from one IP > 100/min". Better still, emit a metric for anything you'd alert on (chapter 100) and keep logs for investigation.

Lab: the cost, the collection and two real bugs

Python 3 logging, the Start Here services, and OpenTelemetry Collector Contrib 0.149's file_log receiver. Times are per log line on the lab machine, averaged over 50,000 lines (3,000 for the fsync cases).

Experiment 1: what a log line costs the caller

Text
text to file                              12.0 µs per line
JSON to file                              14.6 µs per line
JSON to file, fsync every line           224.1 µs per line
JSON via QueueHandler (caller cost)       16.1 µs per line
QueueHandler in front of the fsync handler: 14.6 µs caller cost   (listener needed 0.79 s more to drain)
disabled debug, f-string:     85.62 µs (the string is built, then thrown away)
disabled debug, lazy args:     0.23 µs
bytes per line: text 65  JSON 148

What this shows:

  • JSON formatting is cheap next to everything else. At 15 µs, a service logging 5 lines per request spends 75 µs per request on logging, which matters at thousands of requests per second per core and not otherwise.
  • The sink dominates. Forcing every line to disk (fsync) made logging 15× slower. Network sinks (a remote syslog, an HTTP log API called inline) are worse and can block requests when the receiver is slow.
  • A queue (QueueHandler plus QueueListener, or an async appender in Java's Logback/Log4j 2) moves the slow part off the request path: the caller paid 14.6 µs even with the fsync handler behind it. It didn't help for a fast file, because putting a record on a queue costs about as much as writing it. The price: lines still in the queue when the process dies are lost (0.79 s of backlog here), and an unbounded queue can grow without limit if the sink stalls.
  • Lazy formatting matters most for disabled levels with expensive arguments.

Experiment 2: interleaved lines from threads (a real bug in this volume)

The first version of the Start Here services logged with print(json.dumps(...), flush=True) from a threaded HTTP server. When the Collector read their log, some lines failed to parse:

Text
error  json_parser  invalid character '{' after top-level value
{"ts": ..., "dish": "idli", ..., "trace_id": "9c21ef3f…"}{"ts": ..., "dish": "vada", ...

Two JSON objects on one line. print() writes the text and the newline as two separate writes; with unbuffered output (python3 -u) each is a system call, and another thread can write in between. A standalone reproduction with 8 threads writing 5,000 lines each:

Text
print   : 40000 records written, 38530 non-empty lines, 1226 unparseable
logging : 40000 records written, 40000 non-empty lines, 0 unparseable
lock    : 40000 records written, 40000 non-empty lines, 0 unparseable

About 6% of lines were corrupted. The fix (now in the Start Here code) is to build the whole line including \n and write it once, under a lock; the logging module's handlers already do this. The same class of bug appears in any language when several threads or processes share a stream without line-atomic writes. And note who noticed: the log pipeline's parse errors. Watch your collector's error counters, not just the dashboards built on top.

Experiment 3: collecting a log file with the Collector

YAML
receivers:
  file_log:
    include: [/tmp/V9/orders.log]
    start_at: beginning
    storage: file_storage          # remembers how far it has read
    operators:
      - {type: json_parser, timestamp: {parse_from: attributes.ts, layout: '%Y-%m-%dT%H:%M:%S'},
         severity: {parse_from: attributes.level}}
      - {type: trace_parser, trace_id: {parse_from: attributes.trace_id}}
      - {type: move, from: attributes.msg, to: body}
processors:
  transform/svc:
    log_statements:
      - context: log
        statements: ['set(resource.attributes["service.name"], log.attributes["service"])']

One exported record (OTLP log data model):

Text
resource: {service.name: orders}   severityText: INFO   severityNumber: 9   body: "request"
traceId: df2a2fa8cc9944a181a6593adac0f2d7
attributes: {dish: biryani, route: /order, status: 200.0, duration_ms: 909.6, log.file.name: orders.log}

The text line became a proper log record: real timestamp, severity, the trace ID in the record's trace context field (so backends link it to the trace automatically), and the service as a resource attribute. One detail: status arrived as a double (200.0), because JSON has a single number type; type-sensitive backends may need a conversion so status filters match.

Experiment 4: offsets, restarts and duplicates

Text
lines: 400   first start: 398 exported (two lines held two merged records each, experiment 2)
lines: 800   restart with saved offsets, total exported: 798    (only the 400 new lines read)
             restart with offsets lost,  total exported: 1596   (all 800 read again: duplicates)

A collector remembers its position in each file (here in file_storage; Fluent Bit and Vector have their own checkpoint files). Lose that state (an ephemeral container filesystem, a volume not mounted) and a restart re-ships everything from start_at: beginning, or, with start_at: end, skips whatever was written while it was down. Log pipelines are at-least-once at best: dashboards that count log lines should tolerate duplicates.

Experiment 5: truncating a log a process still has open

While resetting the lab, the log file was emptied with : > orders.log while the service was still writing to it. The next lines landed at the old offset, leaving a hole the filesystem reads back as NUL bytes:

Text
0000000  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0

This is exactly what the copytruncate option of logrotate does to programs that didn't open their log with O_APPEND, and why the first line after rotation is often garbage. Prefer rename-and-reopen rotation (signal the process to reopen its file), or better, log to stdout and let the container runtime handle files.

Try it yourself

  1. Add a redaction or transform step that masks anything resembling an email address in log bodies, and test it with a deliberately bad log line.
  2. Add on_error: drop versus the default to the json_parser and compare what reaches the exporter for the corrupted lines.
  3. Measure a logging.handlers.SysLogHandler over UDP versus TCP with the receiver stopped. Which one blocks?

Revision sheet: logging

Key ideas

  • Structured logs: one event per line, named fields, constant message, UTC timestamps, semantic-convention names.
  • Canonical log lines / wide events: one rich line per request per service.
  • Levels: DEBUG off in production; INFO for significant events; WARN for handled surprises; ERROR for failures.
  • Correlation: trace_id and span_id in every line, injected automatically by the logging integration.
  • Sensitive data: never log secrets; redact at the source and again in the pipeline; separate audit logs.
  • Collection: stdout → node agent (Collector, Fluent Bit, Vector) → backend (Loki, Elasticsearch/OpenSearch, ClickHouse-based, cloud logging); checkpoints; at-least-once.
  • Cost: volume × retention × indexing; sample noisy INFO, drop health checks, tier storage.

Numbers to remember

  • Lab: 12–15 µs per line to a file, 224 µs with fsync per line; disabled f-string debug 85.6 µs vs 0.23 µs lazy; JSON 148 vs text 65 bytes per line; print from 8 threads corrupted ~6% of lines.

Pitfalls

  • Variable messages; inconsistent field names across services.
  • Eager formatting in disabled debug calls.
  • Synchronous network or fsync sinks on the request path.
  • Lines interleaved by threads or processes sharing a stream.
  • Lost collector checkpoints (duplicates or gaps); copytruncate rotation.
  • Secrets, tokens and personal data in logs.

Glossary

  • logfmt: key=value text format, a lighter alternative to JSON.
  • Canonical log line: a single summarising line per request.
  • Checkpoint/offset: a collector's saved read position in a file.
  • Async appender / QueueHandler: hands records to a background thread.
  • Severity number: OpenTelemetry's numeric level (INFO = 9, WARN = 13, ERROR = 17).