TExcelTAD

Structured JSON Logging

A log line like ERROR failed to create link for user 42 after 2003ms is easy for a human and hard for a machine: every query needs a regex, and the regex breaks when someone rewords the message. Structured logs write each event as a set of named fields, almost always one JSON object per line, so tools can filter, aggregate and correlate without parsing prose.

json
{"time":"2026-01-01T10:00:05.123Z","level":"ERROR","msg":"create link failed","service":"linkly","route":"/links","status":500,"duration_ms":2003,"error":"pq: canceling statement due to statement timeout","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7"}

Conventions worth agreeing on

Field Rule
time RFC 3339 in UTC with milliseconds; the collector may also stamp its own time
level a small fixed set: DEBUG, INFO, WARN, ERROR
msg a constant message per event type (create link failed), variables go in fields
service, version, env who wrote it (often added by the collector from Kubernetes metadata)
trace_id, span_id link to the trace (OpenTelemetry); the most valuable fields you can add
error the error text, in its own field; stack traces as one field, not many lines
units in names duration_ms, size_bytes, so nobody has to guess
no secrets, no personal data tokens, passwords, full emails and IPs (where privacy law applies) never reach the log

Write logs to stdout, one JSON object per line, and let the platform collect them (Kubernetes: logs). Don't write log files inside containers, and don't log every successful request at INFO on a busy service unless you're prepared to pay for storing them: metrics already count them. Log the failures, the slow ones and the business events.

Go: log/slog

Go's standard library has had structured logging since Go 1.21 (log/slog). linkly creates one JSON logger at start-up and passes request-scoped loggers down. ReplaceAttr here fixes the time so the output is repeatable; in production you'd leave the real clock:

go · try it yourself
package main

import (
	"context"
	"errors"
	"log/slog"
	"os"
	"time"
)

func main() {
	fixed := time.Date(2026, 1, 1, 10, 0, 5, 123_000_000, time.UTC)
	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo, // DEBUG lines are dropped
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey {
				a.Value = slog.TimeValue(fixed) // only for this example
			}
			return a
		},
	})).With("service", "linkly", "version", "1.5.0")

	// a request-scoped logger: every line carries the request's trace id and route
	reqLog := logger.With("trace_id", "4bf92f3577b34da6a3ce929d0e0e4736", "route", "/links")

	reqLog.Debug("parsing body")                       // below the level: not printed
	reqLog.Info("link created", "code", "q1x9", "duration_ms", 12)
	err := errors.New("pq: canceling statement due to statement timeout")
	reqLog.LogAttrs(context.Background(), slog.LevelError, "create link failed",
		slog.Int("status", 500), slog.Int("duration_ms", 2003), slog.String("error", err.Error()))
	reqLog.Warn("slow redirect", slog.Group("cache", slog.Bool("hit", false), slog.Int("lookup_ms", 40)))
}
{"time":"2026-01-01T10:00:05.123Z","level":"INFO","msg":"link created","service":"linkly","version":"1.5.0","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","route":"/links","code":"q1x9","duration_ms":12}
{"time":"2026-01-01T10:00:05.123Z","level":"ERROR","msg":"create link failed","service":"linkly","version":"1.5.0","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","route":"/links","status":500,"duration_ms":2003,"error":"pq: canceling statement due to statement timeout"}
{"time":"2026-01-01T10:00:05.123Z","level":"WARN","msg":"slow redirect","service":"linkly","version":"1.5.0","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","route":"/links","cache":{"hit":false,"lookup_ms":40}}

Notes: With adds fields to every later line (service, version, trace id); slog.Group nests fields ("cache":{…}); LogAttrs with typed attributes avoids allocations on hot paths. In Python the equivalent is the logging module with a JSON formatter or structlog (Automation Scripting: logging).

Querying JSON logs with jq

Before Loki, there's jq (Automation Scripting: jq): a pod's logs from kubectl logs piped into it answer most questions. One JSON object per line makes that possible:

bash · try it yourself
cat > linkly.log <<'LOG'
{"time":"2026-01-01T10:00:01Z","level":"INFO","msg":"redirect","route":"/{code}","status":302,"duration_ms":4,"trace_id":"a1"}
{"time":"2026-01-01T10:00:02Z","level":"INFO","msg":"redirect","route":"/{code}","status":302,"duration_ms":6,"trace_id":"a2"}
{"time":"2026-01-01T10:00:05Z","level":"ERROR","msg":"create link failed","route":"/links","status":500,"duration_ms":2003,"error":"statement timeout","trace_id":"a3"}
{"time":"2026-01-01T10:00:07Z","level":"WARN","msg":"slow redirect","route":"/{code}","status":302,"duration_ms":480,"trace_id":"a4"}
not json: panic: runtime error: invalid memory address or nil pointer dereference
{"time":"2026-01-01T10:00:09Z","level":"ERROR","msg":"create link failed","route":"/links","status":500,"duration_ms":2001,"error":"statement timeout","trace_id":"a5"}
{"time":"2026-01-01T10:00:11Z","level":"INFO","msg":"link created","route":"/links","status":201,"duration_ms":15,"trace_id":"a6"}
LOG
echo "--- errors:"
jq -Rr 'fromjson? | select(.level == "ERROR") | "\(.time) \(.msg): \(.error) trace=\(.trace_id)"' linkly.log
echo "--- count by level:"
jq -Rn '[inputs | fromjson?] | group_by(.level) | map({(.[0].level): length}) | add' -c linkly.log
echo "--- slowest 2:"
jq -Rr 'fromjson? | select(.duration_ms > 100) | "\(.duration_ms)\t\(.route)\t\(.msg)"' linkly.log | sort -rn | head -2
echo "--- lines that are not JSON:"
jq -Rr 'select(try (fromjson | type != "object") catch true)' linkly.log
--- errors:
2026-01-01T10:00:05Z create link failed: statement timeout trace=a3
2026-01-01T10:00:09Z create link failed: statement timeout trace=a5
--- count by level:
{"ERROR":2,"INFO":3,"WARN":1}
--- slowest 2:
2003	/links	create link failed
2001	/links	create link failed
--- lines that are not JSON:
not json: panic: runtime error: invalid memory address or nil pointer dereference

-R reads raw lines and fromjson? parses each one, silently skipping lines that aren't JSON, which is how one stray panic message (Go's runtime writes panics as plain text to stderr) doesn't break the whole pipeline. The last query finds those lines: a crash is exactly the line you don't want to lose.

Levels and sampling

  • DEBUG off in production by default; make it switchable at runtime (an admin endpoint or a config reload) rather than redeploying.
  • ERROR means someone should look; a "normal" error (a client sent a bad request) is INFO or WARN, or every dashboard of error logs becomes noise.
  • On high-volume paths, sample repetitive logs (one in 100 successful redirects) or log only slow ones. Keep every error.

Test yourself

Why should msg be a constant like "create link failed" with details in fields?

  1. JSON requires it
  2. Constant messages can be counted and grouped; variables in their own fields can be filtered without regexes
  3. To save space
  4. Loki can't index messages

Which field links a log line to a distributed trace?

  1. level
  2. trace_id
  3. time
  4. service

What does jq -R 'fromjson?' do with a line that is not valid JSON?

  1. Stops with an error
  2. Skips it silently
  3. Prints it as a string
  4. Converts it to null