Course contents · Lesson 10 of 22

Structured Logging: Why JSON Logs Beat Plain Text

Logs · Lesson 10 of 22 · 10 min Engineer

Support asks a simple question: "Did user 42's payments fail today, and in which service?" Three services log payments, and each team wrote its lines differently: Payment failed for user 42, ERROR user=42 payment declined and [pay] uid 42 - failure. You try grep 42 and also get order 4211, port 8042 and every timestamp with 42 seconds in it. Structured logging fixes this by writing every event as named fields that a program can read, instead of sentences that only a person can.

The same event as text and as JSON

Here is one failed payment written both ways. The first line is plain text, with the facts embedded in a sentence. The second is JSON (JavaScript Object Notation), a text format of "name": value pairs inside curly braces that every programming language can read. A JSON log holds one complete object per line, a convention called JSON Lines.

2026-11-24 14:02:11 ERROR checkout: payment failed for user 42 on order 9137 after 2350ms
{"timestamp":"2026-11-24T14:02:11.482Z","level":"error","service":"checkout","message":"payment failed","user_id":"42","order_id":"9137","duration_ms":2350}

Both lines hold the same facts, but in the JSON line every fact has a name. The message stays short and constant, and the values that change move into their own fields: user_id, order_id and duration_ms. Because the message never changes, you can count how often "payment failed" happens without the IDs getting in the way.

The same payment failure as a plain-text line on the left and as pretty-printed JSON on the right, with each fact colour-matched across the two
Every coloured fact appears on both sides, but only the JSON side tells a program which fact is which, and only it records the time zone.

Why fields beat free text

Once each fact has a name, you can filter, count and graph by it. "Checkout errors for user 42" becomes an exact test on three fields instead of a guess about word order. "Failed payments per minute" becomes a count of one field value. "Slowest payments today" becomes a sort on duration_ms, which is already a number.

You can try this on your own machine with jq, a small command-line JSON processor (install it with brew install jq on macOS or sudo apt install jq on Ubuntu). Given a file app.log of JSON lines:

# every checkout error, printed as compact one-line JSON
jq -c 'select(.level == "error" and .service == "checkout")' app.log

# how many errors each user had, most first
jq -r 'select(.level == "error") | .user_id' app.log | sort | uniq -c | sort -rn

Log platforms do the same at scale. A shipper, an agent that collects and forwards log lines, parses each JSON line into fields; the store indexes them, and you query by field name. The payoff grows with every service you add: if every team writes user_id, one query finds user 42 everywhere.

Flowchart: the app emits a JSON line, a shipper parses it into fields and adds host and pod, the store indexes each field, and a query for level error and service checkout returns exact matches
Parsing is trivial and exact when the app has already named every field, which leaves the shipper free to add context such as the host and pod.

Standard fields every line should carry

Agree on a small set of fields that every service writes, with the same names and the same types:

  • timestamp in ISO 8601 format and UTC, such as 2026-11-24T14:02:11.482Z. The Z means UTC, so lines from servers in different time zones sort correctly and daylight-saving changes cannot confuse you.
  • level, with one spelling everywhere, such as lower-case error.
  • service: which program wrote the line, such as checkout.
  • message: a short, constant description of the event.
  • trace_id: an ID shared by every log line from the same request, as it passes through each service. A later section covers tracing; for now, know that this one field lets you collect every line of a single request.

Most languages have a library that writes JSON for you. Go's standard library includes log/slog:

log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "checkout")
log.Debug("cart loaded", "items", 3) // below the default INFO level: dropped
log.Error("payment failed", "user_id", "42", "order_id", "9137", "duration_ms", 2350)

On a server whose time zone is UTC, it prints one line. Notice that slog picked its own names, time and msg, and an upper-case level. Libraries differ, which is exactly why teams write down a shared list:

{"time":"2026-11-24T14:02:11.482913Z","level":"ERROR","msg":"payment failed","service":"checkout","user_id":"42","order_id":"9137","duration_ms":2350}

Python teams often use structlog or python-json-logger, and Node.js teams use pino. If you would rather not invent your own list, published ones exist, such as the OpenTelemetry semantic conventions (with names like service.name) and the Elastic Common Schema.

Pitfalls: huge lines, drifting names, secrets

Very large lines. Structured logging makes it tempting to dump a whole request or response body into one field. Lines then grow to many kilobytes, and other systems start cutting them up: Docker splits any line longer than 16 KB into several log entries, and log stores enforce a maximum line size. Log the few fields you need, not whole objects.

Inconsistent field names. If checkout writes user_id, cart writes userId and search writes uid, the store sees three unrelated fields, and a query for one silently misses the other two. Types drift too. If one service sends duration_ms as a number and another as a string such as "2.3s", a store such as Elasticsearch that has already mapped the field as a number rejects the second kind of line.

Secrets. The rule from What Are Logs? still applies, and structured logging makes it easier to break. Logging a whole request object can quietly include its Authorization header or a password field. Log an allow-list of named fields, never entire objects, and use your library's redaction feature where it has one.

Left: a grep pattern finds two of three real failures, misses a line written with uid and falsely matches user 4211. Right: a jq filter on user_id and level finds all three and skips user 4211
The field filter wins only because all three services agreed to call the field user_id, so consistent names are worth as much as the JSON itself.

Keeping logs readable in development

JSON is built for machines, and a wall of braces is hard to read on your laptop. You do not have to give up structure to fix that: keep the fields and change how they are displayed. Pipe the output through a pretty printer, a tool that reformats each JSON line for human eyes:

# indent and colour every line
tail -f app.log | jq .

# or print one short summary line per event
tail -f app.log | jq -r '"\(.timestamp) \(.level) \(.message) user=\(.user_id)"'

Many libraries also have a development mode that prints coloured, aligned text, such as structlog's console renderer or pino-pretty for Node.js. Choose between the two with an environment variable, so production always gets JSON and your terminal gets readable text from the same logging calls.

Check yourself

Why log "message":"payment failed" with a separate user_id field instead of "message":"payment failed for user 42"?

A constant message can be counted as one kind of event, and the user becomes its own field that you can filter on exactly.

What does the Z in 2026-11-24T14:02:11.482Z mean, and why does it help?

It means the time is in UTC, so lines from servers in different time zones sort and compare correctly.

Two services log the same user as userId and user_id. What goes wrong?

The store treats them as two unrelated fields, so a query on either one silently misses the other service's lines.