Logs tell you what the code said; traces tell you where the time went. With the trace ID on every log line, you can open a slow trace and read exactly the log lines written while it ran, or start from an error log and jump to the full request. This guide shows how to add it in the common languages, assuming OpenTelemetry tracing is already set up.

What to add

Two fields from the active span context: trace_id (32 hex characters) and span_id (16 hex characters). Some tools also want trace_flags. Use structured (JSON) logs so the fields are searchable; see structured logging best practices.

{"time":"2026-10-23T09:14:02Z","level":"error","msg":"payment declined","service":"checkout","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7"}

Node.js (pino)

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

export const logger = pino({
  mixin() {
    const ctx = trace.getActiveSpan()?.spanContext();
    return ctx ? { trace_id: ctx.traceId, span_id: ctx.spanId } : {};
  },
});

The OpenTelemetry instrumentations for pino and winston can also add these fields automatically.

Python (logging)

With opentelemetry-instrumentation-logging, set OTEL_PYTHON_LOG_CORRELATION=true and include %(otelTraceID)s and %(otelSpanID)s in your format, or read them in a JSON formatter. See OpenTelemetry for Python.

import logging
from opentelemetry import trace

class TraceFilter(logging.Filter):
    def filter(self, record):
        ctx = trace.get_current_span().get_span_context()
        record.trace_id = format(ctx.trace_id, "032x") if ctx.is_valid else ""
        record.span_id = format(ctx.span_id, "016x") if ctx.is_valid else ""
        return True

Java (Logback with the OpenTelemetry agent)

The Java agent puts trace_id and span_id into the MDC automatically. Add them to your pattern or JSON encoder:

%d{ISO8601} %-5level [%X{trace_id},%X{span_id}] %logger - %msg%n

See OpenTelemetry for Spring Boot.

Go (slog)

func logWithTrace(ctx context.Context, msg string, args ...any) {
	sc := trace.SpanContextFromContext(ctx)
	if sc.IsValid() {
		args = append(args, "trace_id", sc.TraceID().String(), "span_id", sc.SpanID().String())
	}
	slog.InfoContext(ctx, msg, args...)
}

Pass ctx into your logging calls; without it there is no active span to read. See OpenTelemetry for Go.

.NET

ASP.NET Core's logging includes the current Activity trace and span IDs in log scopes; JSON console logging with scopes enabled, or OpenTelemetry's logging provider, outputs them. See OpenTelemetry for .NET.

Background jobs and queues

Workers only have a trace ID if context is extracted from the message and a span is active while processing. Instrument your queue client or extract context manually; see context propagation.

Worked example

During an incident, an alert showed checkout errors rising. Before trace IDs, engineers searched logs by timestamp across five services and argued about which lines belonged together. After adding trace IDs, they opened one failed checkout trace, saw the payment span fail, and read the payment service's log line in the same view: "card network timeout after 10 s". Diagnosis took two minutes.

Common mistakes

  • Logging the trace ID only at the edge, so downstream services' logs are not linked.
  • Logging without context in async code, so the active span is missing.
  • Different field names per service (traceId, trace_id, traceid), which breaks search; agree on one.
  • Plain-text logs that tools cannot parse into fields.

In VitalRix

Logs sent with the trace ID appear inside the trace, and every log line links back to its trace. See logs, metrics and traces and log aggregation.

Checking that it works

Pick one request, find its trace, and search your logs for its trace ID. You should see log lines from every service the request touched, in order. If lines from one service are missing, that service either does not propagate context or logs outside the active span (for example in a callback or thread pool). Fix those gaps one service at a time, starting with the services most often involved in incidents. For the logging side, see log levels and log aggregation.

Privacy reminder

Trace IDs are random and safe to log. The rest of the log line is where secrets and personal data slip in: keep tokens, passwords and full request bodies out, and use internal IDs instead of names or emails.

Do I need tracing to add trace IDs to logs?

Yes. The trace ID comes from the active span, so the service must be instrumented with OpenTelemetry or another tracing library.

Should I log the span ID too?

Yes. It shows which span within the trace wrote the line, which helps in long traces.

What field name should I use?

Pick one across all services; trace_id and span_id are common and match OpenTelemetry conventions for logs.

Try VitalRix free

Uptime monitoring, APM, logs, real user monitoring and status pages in one place. No credit card needed.