During an incident last quarter we pasted two hundred log lines into an AI assistant and asked why checkout was failing. It produced a confident answer about a database timeout. The real cause was a card-network decline, and the timeout lines came from a different request that happened to be interleaved. Nothing in the logs said which lines belonged together, so the assistant did what a tired engineer would do: it matched on the scariest words.

The fix was not a better prompt. It was better logs. This guide is the log format we now use across Python, Node and Go services, why each field exists, and how it lets both people and AI tools answer "what happened to this request" with a filter instead of a guess.

The fields every line carries

We settled on a small, fixed set. Every service emits these on every line, with the same names:

Field

Example

Why

ts

2027-01-08T09:14:03.512Z

UTC, ISO 8601, millisecond precision

level

info

Lowercase, one of debug/info/warn/error

service

orders-api

Which deployable wrote it

version

1.43.0

Ties a line to a deploy

env

prod

Prevents staging lines polluting a prod query

event

payment.capture.failed

Stable machine name of what happened

msg

capture declined by issuer

Short human sentence

trace_id

4bf92f3577b34da6a3ce929d0e0e4736

Joins lines across services

span_id

00f067aa0ba902b7

Joins a line to one operation

request_id

req_7Hq2...

Our edge ID, returned to the client

Anything else goes in as extra keys, never inside msg. order_id=ord_123 as a field can be filtered; "failed to capture order ord_123" in a sentence has to be parsed.

Correlation: trace IDs, not home-grown IDs

If you run OpenTelemetry, the trace ID already exists and is propagated between services in the W3C traceparent header:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01

The second field is the 32-hex-character trace ID, the third is the parent span ID. Put the current trace and span IDs on every log line and you can jump from any line to the full trace, and from a trace to every line it produced. The OpenTelemetry log data model has TraceId and SpanId as top-level fields for exactly this reason.

We still keep a separate request_id generated at the edge. It is short, it is returned to the client in a response header, and support staff can ask a customer for it. The edge logs both, which links a support ticket to a trace.

Python: structlog with context variables

structlog keeps per-request context in contextvars, so you bind once at the start of the request and every later line in that task carries it:

import logging
import structlog
from opentelemetry import trace

def add_trace_ids(_, __, event_dict):
    ctx = trace.get_current_span().get_span_context()
    if ctx.is_valid:
        event_dict["trace_id"] = format(ctx.trace_id, "032x")
        event_dict["span_id"] = format(ctx.span_id, "016x")
    return event_dict

structlog.configure(
    processors=[
        structlog.contextvars.merge_contextvars,
        structlog.processors.add_log_level,
        structlog.processors.TimeStamper(fmt="iso", utc=True, key="ts"),
        add_trace_ids,
        structlog.processors.dict_tracebacks,
        structlog.processors.EventRenamer("msg", replace_by="_event"),
        structlog.processors.JSONRenderer(),
    ],
    wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
)

log = structlog.get_logger().bind(service="orders-api", version="1.43.0", env="prod")

def handle_capture(request_id: str, order_id: str):
    structlog.contextvars.bind_contextvars(request_id=request_id, order_id=order_id)
    log.info("capture started", _event="payment.capture.started")

structlog stores the first positional argument under its own event key, so passing event= as a keyword collides with it. EventRenamer("msg", replace_by="_event") moves the sentence to msg and promotes our _event keyword to event. The important part is the processor order: context first, trace IDs before rendering, JSON last.

Node: pino with a mixin

pino calls mixin() for every line, which is the right place to read the active span:

import pino from "pino";
import { trace } from "@opentelemetry/api";

export const log = pino({
  base: { service: "checkout-web", version: process.env.APP_VERSION, env: process.env.APP_ENV },
  timestamp: pino.stdTimeFunctions.isoTime,
  messageKey: "msg",
  formatters: { level: (label) => ({ level: label }) },
  mixin() {
    const ctx = trace.getActiveSpan()?.spanContext();
    return ctx ? { trace_id: ctx.traceId, span_id: ctx.spanId } : {};
  },
  redact: {
    paths: ["req.headers.authorization", "req.headers.cookie", "*.password", "*.card_number"],
    censor: "[REDACTED]",
  },
});

log.warn({ event: "payment.capture.failed", order_id: "ord_123", decline_code: "do_not_honor" },
  "capture declined by issuer");

The formatters.level line makes pino write "level":"warn" instead of the numeric 40, so every service uses the same values.

Go: slog with a handler wrapper

Go's standard log/slog has a JSON handler. A thin wrapper adds the trace IDs from the context:

type traceHandler struct{ slog.Handler }

func (h traceHandler) Handle(ctx context.Context, r slog.Record) error {
	if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
		r.AddAttrs(slog.String("trace_id", sc.TraceID().String()),
			slog.String("span_id", sc.SpanID().String()))
	}
	return h.Handler.Handle(ctx, r)
}

logger := slog.New(traceHandler{slog.NewJSONHandler(os.Stdout, nil)}).
	With("service", "billing-worker", "version", version, "env", env)

logger.ErrorContext(ctx, "ledger write failed", "event", "ledger.write.failed", "order_id", id)

Use the ...Context variants (InfoContext, ErrorContext) everywhere, or the handler never sees the span.

Event names are an API

event is the field we filter on most, so we treat it like a public API:

  • Dot-separated, lowercase, domain.object.action: payment.capture.failed, order.created, auth.token.refresh.failed.

  • Past tense for things that happened, .started/.completed pairs for long operations.

  • Never interpolate values into the name. payment.failed.ord_123 makes every order a new event.

  • A short registry file (docs/log-events.md) lists every name with its owner. A rule script in CI warns on names not in the registry.

With stable names, "show me every payment.capture.failed in the last hour grouped by decline_code" is a one-line query in any backend, and an AI assistant can write it reliably because the vocabulary is fixed.

What context to log, and what not to

Log what you would need to reproduce the decision the code made: identifiers (order, tenant, plan), the branch taken, the external status code, durations, retry counts. Log the input shape rather than the input when it is large: items_count=14, not the full cart.

Do not log secrets, tokens, full card numbers, passwords or raw request bodies. Hash or drop personal data such as email addresses unless you have a clear need and a retention policy for it. We use three layers:

  1. Logger redaction for known paths, as in the pino redact option above.

  2. Allowlisted fields for request and response logging: we log named headers, not all headers.

  3. Collector-side scrubbing as a backstop, so a mistake in one service does not reach storage.

Our earlier post on redacting personal data from LLM prompts and logs goes deeper into patterns and testing.

Making it work for AI-assisted debugging

Once the logs are structured, the workflow changes. Instead of pasting raw lines, we give the assistant a filtered slice:

# all lines for one trace, oldest first, only the fields that matter
jq -c 'select(.trace_id=="4bf92f3577b34da6a3ce929d0e0e4736")
       | {ts, service, level, event, msg, decline_code, status, duration_ms}' \
  prod-2027-01-08.jsonl | sort

Fifteen lines from three services, in order, with no interleaving, is something both a person and a model read correctly. The assistant can also propose its own follow-up query because it knows the field names, and we can run that query and check its claim against data rather than trusting the narrative.

Common mistakes

Mistake

Why it hurts

Do this instead

Values inside msg

Cannot filter or group

Separate fields

Different field names per service

Cross-service queries break

One shared field set, shared config package

No trace ID on lines

Cannot join logs to traces

Inject from the active span on every line

Logging whole payloads

Cost and data exposure

Log shapes, IDs and decisions

Free-form event names

Vocabulary drifts, queries rot

Registry of domain.object.action names

Key takeaways

  • Every line needs the same small field set, including trace_id, span_id and a stable event.

  • Reuse the OpenTelemetry trace ID for correlation and keep a short edge request_id for support.

  • Treat event names as an API with a registry and a CI check.

  • Redact at the logger, allowlist request fields and scrub again at the collector.

  • Give AI assistants a filtered, ordered slice for one trace, never a raw interleaved dump.

References