BEGINNERCHAPTER 03

Structured logging done properly

One wide, machine-readable line per request, a trace id on every line, few labels, and never a secret

50 MINOBSERVABILITYUPDATED 2026-11-02
PREDICT

You ship JSON logs from the orders service to Loki. A colleague proposes making user_id and trace_id Loki labels so that queries for one user or one request are fast. There are 1000 users and 5 requests per second. What happens?

The three-signals chapter put a trace id in a log line by hand, inside a printf-style message. It worked because you knew exactly what to grep for. This chapter replaces that habit with a discipline: logs as records with named fields, one dense line per request, levels that mean something, a short list of things that are never logged, and a log store whose index you do not blow up. You will finish by finding a planted PII leak with a LogQL query in under a minute.

Why printf logs fail at scale

A printf log is a sentence for a human: charge failed for order 18231 after 2.1s. It reads well in a terminal with one process and ten lines a second. It fails in four ways once you have fifty services and ten thousand lines a second.

Every query is a regex against an unpromised format. To find slow charges you write grep -E 'after [0-9]+\.[0-9]+s'. Next week someone changes the message to charge failed (order=18231, took 2100ms), and your alert silently stops matching. The format was never a contract, so nothing breaks loudly.

Fields are ambiguous. In user 42 order 18231 3 items 2.1, which number is which? A human can guess from position; a parser has to be told, per message, per service, per version.

You cannot aggregate. “Average charge duration by provider over the last hour” needs the duration and the provider as fields. From prose you parse every line in the window, at query time, with a regex per message variant.

Lines are scattered. One request writes eight lines across three services: “received”, “validated”, “inserted”, “calling payments”, “charged”, “done”. To answer anything about the request you have to find all eight and join them by timestamp or by an id that some lines carry and some do not.

The first three are fixed by structure: every line is a set of named fields. The fourth is fixed by the canonical log line: one wide line per request that carries everything you would otherwise have to join.

key=value and JSON

There are two structured formats in common use.

logfmt, key=value pairs separated by spaces, came out of Heroku and is what Stripe’s canonical lines use:

ts=2026-11-02T03:10:04.212Z level=info service=gateway msg="checkout done" user=42 items=3 status=200 duration=2120ms trace_id=4bf92f3577b34da6a3ce929d0e0e4736

JSON, one object per line (sometimes called NDJSON), is what most log libraries, collectors and stores default to:

{"ts":"2026-11-02T03:10:04.212Z","level":"info","service":"gateway","msg":"checkout done","user":42,"items":3,"status":200,"duration":"2120ms","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}

logfmt is easier for a human to read in a terminal and slightly smaller. JSON has types (numbers stay numbers, nesting is possible), is unambiguous about quoting, and every tool parses it. LogQL has a parser for each: | logfmt and | json. Pick one per organisation and enforce it; this course uses JSON, which the demo app emits when LOG_FORMAT=json.

Three rules make structured logs useful rather than merely parseable. Use stable, consistent field names across services: duration, not duration in one and elapsed_ms in another and took in a third. OpenTelemetry’s semantic conventions (http.request.method, http.response.status_code, url.path) are a ready-made vocabulary. Put the unit in the value or the name: "duration":"2120ms" or "duration_ms":2120, never a bare 2120. LogQL’s duration comparison (duration > 500ms) only works when the value is a string with a unit suffix; a bare number needs a number comparison on a field whose name tells you the unit. Keep the message constant and put the variables in fields: msg="checkout done" with user=42, not msg="checkout done for user 42". A constant message is something you can count by.

The canonical log line

Brandur Leach described the pattern at Stripe: in addition to whatever ordinary log lines a request emits, emit one line at the end of each request that contains everything about it. Stripe’s examples carry the HTTP method and path, status, duration, the authenticated user and API key, rate-limit state, the number of database queries, the time spent in the database, and the git revision. Each line has dozens of fields. It is a log line in transport and a wide event in spirit: the wide-events chapter in module three takes the idea to its conclusion.

Why it works: almost every question during an incident is answerable from one row per request. Which routes are slow? | json | duration > 1s grouped by path. Is it one user? Group by user. Is it the new version? Group by service_version. Did it start with the database? Look at db_ms. None of these need a join across lines, because the line already carries the joined result.

For the gateway in the demo app, a good canonical line has: msg="canonical", http.request.method, http.route, http.response.status_code, duration, user, items, vip, order_id, orders_ms (time in the downstream call), trace_id, and span_id, with service.version coming from the resource. That is about 400 bytes. You will write it in the lab.

Where it goes wrong:

  • Emitted in the happy path only. If the line is written after the response and an exception skips it, the requests you most need are missing. Write it in a finally or in middleware that wraps the handler.
  • Too wide. Copying the whole request body into the line is how PII and multi-kilobyte lines happen. Fields are chosen, not dumped.
  • Duplicated by every layer. One canonical line per service per request. If three middlewares each write their own, you have three half-lines again.

Levels, and what to log at each

Log levels are a volume control and a severity hint. Most codebases use them inconsistently, so the useful thing is a team rule for each. The OpenTelemetry log data model maps them to severity numbers: INFO is 9 to 12, WARN 13 to 16, ERROR 17 to 20.

Level Meaning Example In production
DEBUG detail for a developer working on this code the SQL text and bind values for each query off, or sampled; turned on per service when needed
INFO a normal unit of work completed the canonical line; startup with config summary on; this is most of your volume
WARN something unexpected happened and the system coped a retry succeeded on the second attempt; a fallback was used on; someone should look at the rate, not each line
ERROR a unit of work failed and a user or caller saw it the charge returned 500; the request was abandoned on; carries the exception and stack

Two common mistakes. Logging ERROR for things that are not errors, such as a 404 for a missing resource, which trains everyone to ignore ERROR. And logging an error at every layer it passes through, so one failure produces five ERROR lines with five stack traces. Log an error once, where it is handled, and let the canonical line record the outcome.

Request ids and trace ids

A line without an id that ties it to a request is nearly useless in a concurrent service. Before distributed tracing, services minted a request id at the edge (often from an X-Request-Id header set by the load balancer), passed it downstream, and logged it on every line. That still works, and many load balancers still set one.

With OpenTelemetry in place, the trace id does the same job and also links to the trace. The Python logging instrumentation, with OTEL_PYTHON_LOG_CORRELATION=true, injects otelTraceID, otelSpanID, otelServiceName and otelTraceSampled into every logging.LogRecord, so a JSON formatter can write them as trace_id and span_id without any per-call code. The lab app gets the same result another way: its JSON formatter (services/common/logging_setup.py) reads the current span itself, and the OTLP log handler that ships records to Loki stamps the ids on every record, which is why every line from now on carries trace_id. If your edge already has a request id that support staff and customers quote, log both: the request id is what people will paste into a search box, the trace id is what joins the signals.

What never to log

The OWASP Logging Cheat Sheet’s list of data to exclude is the right baseline. Never write these to a log, in any field, at any level:

  • Secrets: passwords, API keys, access and refresh tokens, session ids, database connection strings, encryption keys.
  • Payment data: card numbers, CVVs, card-holder names together with card data. PCI DSS makes this a compliance failure, not a style issue.
  • Sensitive personal data: government ids, health data, precise location, and anything a user has not consented to you processing for this purpose.

Ordinary personal data (names, emails, phone numbers, IP addresses) is a judgment call governed by your privacy policy and GDPR or its local equivalent; the default should be an internal id instead of the value. A user id lets you find the request; it does not put the user’s name in front of every engineer with log access for a year.

The leaks are rarely deliberate. They come from logging a whole object (log.info("request: %r", req)), from exception messages that include the input that caused them, and from DEBUG left on. The defences are layered: log chosen fields not objects; use typed wrappers for secrets whose __repr__ returns ***; and scrub in the pipeline as a backstop, which the O2 project builds with the Collector’s processors. The backstop is not the fix: a scrubber can only remove patterns it knows.

Sampling and the cost of a line

A log line looks free. At volume it is not. The demo gateway’s canonical line is about 400 bytes. At 1000 requests per second that is 400 kB per second, 34.5 GB a day, from one line on one service. Grafana Cloud’s published pay-as-you-go rate for logs is $0.40 per GB written plus retention and processing, so that one line costs on the order of $14 a day, $5000 a year, before you count the eight other lines each request writes in each of three services. Self-hosted, the cost is disk, network and the CPU of compression and querying instead of an invoice, but it scales the same way.

The levers, in the order you should pull them:

  1. Write fewer, wider lines. Replacing eight narrative lines per request with one canonical line usually cuts volume by more than half while making queries easier.
  2. Turn DEBUG off in production, and keep the ability to turn it on for one service at runtime.
  3. Sample the boring successes. Keep every ERROR and WARN and every slow request; keep 1 in 10 or 1 in 100 of the fast 200s, and record the sample rate as a field (sample_rate=100) so counts can be multiplied back up. Make the decision once per request, keyed on the trace id, so that you keep all of a request’s lines or none.
  4. Shorten retention for INFO and keep ERROR longer. Most queries look at the last 24 hours.

Loki’s label discipline

Loki is the log store in the lab, and it has a design that rewards one habit and punishes its opposite.

Loki does not index the content of log lines. It indexes a small set of labels per stream. A stream is the sequence of lines that share exactly the same label set, such as {service_name="orders", deployment_environment="lab"}. Lines in a stream are compressed into chunks; the index maps label sets to chunks. A query first selects streams by label (the part in braces), then scans the chunks of those streams for the time range, applying line filters and parsers to every line.

That design makes ingestion and storage cheap and makes two things expensive. A query whose label selector matches a lot of data has to decompress and scan all of it; narrow selectors and short time ranges matter. And high-cardinality labels create huge numbers of tiny streams, each with its own index entries and its own small chunks. Grafana’s label guidance says labels should have low cardinality, “ideally limited to tens of values”, and states plainly: do not put ephemeral values such as a trace id or an order id in a label. User ids fall under the same rule.

So the discipline is: few, low-cardinality labels that describe where a line came from (service, environment, cluster, namespace), and everything else in the line, extracted at query time with a parser. When you ingest over OTLP, Loki promotes a fixed set of resource attributes (such as service.name, service.namespace, deployment.environment.name, k8s.namespace.name) to labels, converting dots to underscores, and stores the remaining attributes as structured metadata: per-line key-value pairs that are not indexed but can be filtered without parsing. Structured metadata is the right home for a trace id when you query by it often. The lab’s loki/loki.yaml promotes service.name, deployment.environment and service.version, which is why the queries use {service_name="orders"}. The lab’s services ship logs to Loki over OTLP, not as JSON text: the Loki line is the log message (request, order paid) and every field, trace_id included, is structured metadata. So in the lab you filter fields directly, | ms > 500, with no parser; | json is for stores that hold the JSON text itself.

The LogQL you need for this chapter is four pieces:

Piece Example What it does
stream selector {service_name="orders"} picks streams by label; required
line filter |= "charge", != "healthz", |~ "(?i)timeout" substring or regex match on the raw line; cheap, run it first
parser | json, | logfmt extracts fields as labels for this query only; nested JSON keys are flattened with _
label filter | duration > 500ms, | status >= 500, | user = "42" filters on extracted fields or structured metadata with typed comparisons: string, number, duration, bytes

And one metric query, to turn lines into a number: sum by (http_route) (count_over_time({service_name="gateway"} | duration > 1s [5m])).

LAB Structured logs, a canonical line, and a leak ~40 MIN
YOU NEEDDocker Desktop or Docker Engine with Compose v2 and about 4 GB of RAM freethe ATLAS repo cloned (labs/observability), with the three-signals lab workingcurl and jqa browser for Grafana on localhost:3000

You will switch the demo app to JSON logs, query them with LogQL, add a canonical log line to the gateway, then plant a PII leak and find it.

1. Switch to JSON logs.

cd labs/observability
OTEL_SDK_DISABLED=false LOG_FORMAT=json FAULT_SLOW_PAYMENTS_PCT=5 docker compose --profile telemetry up -d
docker compose logs --since 30s orders | tail -n 3
Each line is now one JSON object, for example {"ts":"...","level":"INFO","service":"orders","logger":"orders","msg":"request","trace_id":"...","span_id":"...","method":"POST","route":"/orders","status":200,"ms":812.4}. The fields after msg are the extra={...} the code passed, merged into the top level; ms is a number of milliseconds, its unit in its name. The trace and span ids come from the current span, not written by hand in each call. This is the container’s stdout. Loki gets the same record over OTLP: the line is the message, request, and every field rides beside it as structured metadata.

2. Query the slow orders in Loki.

In Grafana (http://localhost:3000, admin / admin) open Explore, pick Loki, switch the editor to Code, and run:

{service_name="orders"} | route="/orders" | ms > 500

Then, from a shell, the same query over the HTTP API:

curl -s -G 'http://localhost:3100/loki/api/v1/query_range' \
  --data-urlencode 'query={service_name="orders"} | route="/orders" | ms > 500' \
  --data-urlencode 'since=15m' --data-urlencode 'limit=20' \
  | jq -r '.data.result[].stream | [.ms, .trace_id] | @tsv'
A few lines per minute, every one with ms between about 1500 and 3000, which is the slow-payments fault seen from orders (orders waits for payments). No parser ran: route and ms are structured metadata, and the API returns them in each result’s stream object next to the real labels. ms is a bare number, so the comparison is numeric; ms > 500ms would fail, because a duration comparison needs a value with a unit. Grafana shows the fields in each line’s details, and trace_id is a link to Tempo through the derived field from the last chapter. Now count them as a metric:
sum(count_over_time({service_name="orders"} | route="/orders" | ms > 500 [1m]))
A graph hovering around 15 per minute: 5 percent of 5 requests per second is 0.25 per second. You have turned log lines into a time series at query time, which is useful for a question you did not anticipate and too slow to put on an always-on dashboard; the metrics chapter does the same thing properly.

3. Add a canonical log line to the gateway.

Every service already writes one line per request from the request_log middleware in services/common/app.py. Turn that line into a canonical one. It has to stay in create_app: the OpenTelemetry middleware is added there after it, so it wraps it and the request’s span is current when the line is written; a middleware you add later in gateway/app.py would run outside the span and log a zero trace id. Replace the request_log function with:

    @app.middleware("http")
    async def request_log(request: Request, call_next):
        start = time.perf_counter()
        request.state.fields = {}          # handlers add fields here
        status = 500
        try:
            response = await call_next(request)
            status = response.status_code
            return response
        finally:
            if request.url.path not in ("/health", "/metrics"):
                route = getattr(request.scope.get("route"), "path", request.url.path)
                ms = (time.perf_counter() - start) * 1000
                log.info("canonical", extra={
                    "http.request.method": request.method,
                    "http.route": route,
                    "http.response.status_code": status,
                    "duration": f"{ms:.1f}ms",
                    **request.state.fields,
                })

The trace and span ids are added by the formatter and the OTLP handler, and the version is already on every record as the resource attribute service.version (compose sets it from SERVICE_VERSION), so neither goes in the fields. Then open services/gateway/app.py. Remove the log.info("checkout done ...") line you added in the last chapter, add request: Request to the checkout signature (import Request from fastapi), and record what only the handler knows, directly after order_id = body.get("order_id"):

    request.state.fields.update(user=user, items=effective_items, vip=vip,
                                order_id=order_id, orders_ms=ms)

ms at that point is the time until orders answered. Rebuild all three services, since they share common/:

OTEL_SDK_DISABLED=false LOG_FORMAT=json FAULT_SLOW_PAYMENTS_PCT=5 docker compose --profile telemetry up -d --build gateway orders payments
curl -s 'http://localhost:8080/checkout?user=42&items=3' > /dev/null
docker compose logs --since 20s gateway | grep '"canonical"' | tail -n 1
One line per request, about 400 bytes, with every field named. The finally block guarantees the line is written even when the handler raises, in which case status stays 500 and the line still carries the trace id. On stdout the line carries "msg": "canonical", the trace and span ids, the HTTP fields, "duration": "812.4ms" (a string with a unit this time, so LogQL’s duration comparison works on it) and, on the gateway, user, items, vip, order_id and orders_ms. In Loki the line is canonical and the fields are structured metadata, with dots turned to underscores (http_route, http_response_status_code).

4. Ask the questions the last two chapters could not.

{service_name="gateway"} |= "canonical" | user="42"
sum by (vip) (count_over_time({service_name="gateway"} |= "canonical" | duration > 1s [5m]))
quantile_over_time(0.99, {service_name="gateway"} |= "canonical" | unwrap duration(duration) [5m]) by (service_version)
The first returns every checkout for user 42 with its duration, its orders_ms, and a trace link: the first chapter’s question, answered from one line per request. The second shows whether slowness is concentrated on VIP users (it is not; the payment fault is random), which is the high-cardinality slicing a metric with a vip label could also do but a user label could not. The third computes p99 by version from the logs, grouping by the service_version stream label; unwrap duration(duration) converts the string to seconds. It works, and it scans every line in the window to do it.

5. Plant a PII leak and find it.

FAULT_LEAK_PII=1 OTEL_SDK_DISABLED=false LOG_FORMAT=json FAULT_SLOW_PAYMENTS_PCT=5 docker compose --profile telemetry up -d payments

You are told only that payments may be logging personal data. In Grafana Explore, start broad and narrow:

{service_name="payments"} |= "charge captured"
docker compose logs --since 2m payments | grep -ciE 'name|holder|card'
{service_name="payments"} | card_holder != ""
Expand a recent line from the first query: with the fault on, its fields include a new one, card_holder, with a value like Ada Lovelace. A regex line filter such as |~ "(?i)holder" would not find it, because a Loki line filter searches the line, and here the line is only the message; the name sits in structured metadata. The second command finds it in the container’s stdout, where the JSON formatter wrote every field into the text. The third confirms it field-wise in Loki: every charge since the restart has leaked a name. In a real incident your next step is a query over the whole retention window, count_over_time({service_name="payments"} | card_holder != "" [30d]), to report how many records were exposed and for how long, followed by deleting the affected data.

6. Check the damage with the label API.

curl -s -G 'http://localhost:3100/loki/api/v1/labels' --data-urlencode 'since=1h' | jq -c .data
curl -s -G 'http://localhost:3100/loki/api/v1/series' --data-urlencode 'match[]={service_name="payments"}' --data-urlencode 'since=1h' | jq '.data | length'
A short list of label names (service_name, deployment_environment, service_version) and one payments stream. The leak is confined to structured metadata, not the labels; had someone made the name a label, it would also sit in the index and in every series listing. Switch the fault off before moving on, keeping the SDK and JSON logs on: OTEL_SDK_DISABLED=false LOG_FORMAT=json docker compose --profile telemetry up -d payments.
Make trace_id a Loki label. In otel/collector.yaml, add a transform processor to the logs pipeline that copies the trace id into a resource attribute (set(resource.attributes["trace_id"], trace_id.string) in the log context), add trace_id to the index_label list in loki/loki.yaml, run docker compose restart otel-collector loki, and raise the load with LOADGEN_RPS=50 docker compose up -d loadgen. After five minutes, re-run the series query from step 6: the payments stream count goes from one to tens of thousands, one per request. Run {service_name="orders"} |= "canonical" | duration > 500ms over the last hour and time it; it is markedly slower, because the querier opens a chunk per stream instead of a few large ones. You have reproduced, at lab scale, the most common way teams take down their own Loki. Revert both files and restart the two containers, put the load back with docker compose up -d loadgen, and restore the stock services with git checkout -- services/common/app.py services/gateway/app.py and a rebuild of all three: the later labs use the stock log lines.
DECIDE

Your log bill has tripled in a year. The biggest service, checkout-api, writes about nine lines per request at 4000 requests per second: received, validated, cart loaded, pricing done, calling payments, payment ok, order saved, response sent, and an access log. Finance wants a 60 percent cut this quarter. You own the decision.

READING
  1. POST
    Fast and flexible observability with canonical log lines Brandur Leach, Stripe, 2019

    Stripe's account of the pattern in production, with example fields and how the lines feed both incident queries and a data warehouse. Read it for which fields earned their place; the warehouse pipeline is for module four.

  2. POST
    Canonical log lines Brandur Leach, 2016

    The original, shorter post that named the pattern, in logfmt, with the argument for a middle tier between metrics and raw log traces. Ten minutes and worth it for the field list alone.

  3. DOC
    LogQL log queries

    The reference for everything in the lab: stream selectors, line filters, the json and logfmt parsers and their flattening rules, and typed label filters including duration and bytes. Read the parser and label filter sections; the formatting stages can wait.

  4. DOC
    Label best practices (Loki)

    Grafana's own rules for labels: static over dynamic, tens of values, never ephemeral ids, and how to find the offending label with logcli. Short and directly applicable to the break-it step.

  5. DOC
    Structured metadata (Loki)

    Where high-cardinality fields such as trace ids belong when you query them often: attached to each line, not indexed, filterable without a parser. Read it with the OTLP ingestion page, which says which resource attributes become labels.

  6. DOC
    OWASP Logging Cheat Sheet

    The baseline list of what to log for security and what never to log, with the reasoning. The 'data to exclude' section is the one to adopt as team policy; skip the event-attribute detail on first read.

  7. DOC
    OpenTelemetry logging instrumentation for Python

    How otelTraceID and otelSpanID get onto every log record, the OTEL_PYTHON_LOG_CORRELATION switch and the default format string. Two pages; it is what the lab app's JSON formatter builds on.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Metrics 101: counters, gauges, histograms, and cardinality →