Structured logging best practices: JSON logs, a consistent schema, trace correlation and cost control
How to design JSON logs that machines and humans can both use, align them with the OpenTelemetry log data model, connect every line to its trace, keep secrets out and keep volume under control.
Summary
- Structured logging best practices start with one JSON object per event, a fixed set of field names aligned with OpenTelemetry semantic conventions, and severity levels that mean the same thing in every service.
- Adding trace_id and span_id to every log record turns logs from an isolated text stream into evidence you can navigate from and to distributed traces.
- Secrets and personal data should never reach storage, and log volume is best controlled in a telemetry pipeline with filtering and sampling rather than by deleting log statements under pressure.
Structured logging best practices are less about a specific library and more about a contract: every log event is a machine-readable record with predictable field names, a meaningful severity and enough context to answer a question during an incident. Plain text lines like user 4711 failed to pay after 3 retries are easy to write and hard to query. The same event as JSON with user.id, retry.count and trace_id fields can be filtered, aggregated and joined with traces in seconds.
This guide covers the format, a field schema based on the OpenTelemetry log data model, log level rules, correlation with traces, what you must never log, how to control volume and cost, and copyable examples for Python, Node.js, Java and Go. It ends with a field reference table and a checklist for code reviews.
Why structured logs beat free-text lines
Structured logging means emitting key-value data instead of prose. In practice that is almost always JSON, one object per line, written to stdout or a local file and collected by an agent or the OpenTelemetry Collector.
- Queries instead of regular expressions. Filtering on
http.response.status_code >= 500is reliable; parsing the same value out of ten different message formats is not. - Aggregation. Counting errors by
error.typeor by route works only if those values live in their own fields. - Stable parsing. A developer rewording a message does not break dashboards or alerts, because they depend on fields, not on text.
- Correlation. A
trace_idfield lets you jump from a log line to the full request across services.
Keep the human-readable message, though. A short, constant message such as "payment failed" plus fields is the best of both worlds: readable in a terminal, groupable in a backend.
A consistent field schema based on the OpenTelemetry log data model
The biggest practical problem in log analysis is not missing data but inconsistent names: userId in one service, user_id in the next and uid in a third. Pick one schema and enforce it. The OpenTelemetry log data model is a good foundation because it is vendor-neutral and maps directly to OTLP. According to the specification, a log record has these top-level fields:
- Timestamp and ObservedTimestamp: when the event happened and when it was collected.
- TraceId, SpanId and TraceFlags: the trace context of the request that produced the record.
- SeverityText and SeverityNumber: the original level name and a normalized number.
- Body: the message itself, a string or structured value.
- Resource: who produced the record, for example
service.name,service.version,deployment.environment.name, host or Kubernetes pod. - InstrumentationScope, Attributes and EventName: the logger that emitted it, event-specific key-value data, and an optional name that marks the record as a typed event.
For attribute names, reuse the OpenTelemetry semantic conventions wherever one exists: http.request.method, http.route, http.response.status_code, url.path, exception.type, exception.message, exception.stacktrace, error.type, user.id. For domain fields that have no convention, define your own namespace (for example shop.order.id) and document it. Watch cardinality: IDs belong in log attributes, but they should not be promoted to metric labels.
An example record that follows these rules:
{
"timestamp": "2026-10-28T09:14:03.221Z",
"level": "ERROR",
"message": "payment failed",
"service.name": "checkout-api",
"service.version": "2026.10.4",
"deployment.environment.name": "production",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"span_id": "00f067aa0ba902b7",
"http.route": "/orders/{id}/pay",
"http.response.status_code": 502,
"error.type": "PaymentProviderTimeout",
"shop.order.id": "ord_8f3k2",
"retry.count": 3
}
Log levels that mean the same thing everywhere
A log level is only useful if all teams use it the same way. The OpenTelemetry data model normalizes levels to a SeverityNumber from 1 to 24 in six ranges, so records from different languages can be compared:
| Level | SeverityNumber | Use it for | Production default |
|---|---|---|---|
| TRACE | 1–4 | Very detailed flow, loop iterations | Off |
| DEBUG | 5–8 | Diagnostic detail for developers | Off, enable temporarily per service |
| INFO | 9–12 | Business-relevant events: started, order placed, job finished | On |
| WARN | 13–16 | Unexpected but handled: retry, fallback, slow dependency | On |
| ERROR | 17–20 | An operation failed and needs attention | On |
| FATAL | 21–24 | The process cannot continue | On |
Three rules prevent most level problems. First, log an error once, where it is handled, not at every layer it passes through. Second, an expected client mistake (a 404 or a validation failure) is not an ERROR; reserve that level for things someone should look at. Third, make the level configurable at runtime through an environment variable or configuration, so you can raise verbosity for one service during an investigation without a redeploy.
Correlating logs with traces via trace_id and span_id
A log line tells you what happened; a trace tells you where in the request it happened and what else was slow. Connecting both is one of the most valuable structured logging best practices. The OpenTelemetry specification for trace context in non-OTLP log formats recommends top-level JSON fields named trace_id and span_id, lowercase hex-encoded, plus an optional trace_flags.
You rarely have to add them by hand. The official instrumentation for the major logging libraries does it for you, as long as tracing is active:
- Python:
opentelemetry-instrumentation-loggingaddsotelTraceID,otelSpanID,otelServiceNameandotelTraceSampledto eachLogRecord; setOTEL_PYTHON_LOG_CORRELATION=trueto also change the default log format. - Node.js:
@opentelemetry/instrumentation-pino(and the Winston and Bunyan equivalents) injectstrace_id,span_idandtrace_flagsand can also send records to the OpenTelemetry Logs SDK. - Java: the OpenTelemetry Java agent puts
trace_id,span_idandtrace_flagsinto the MDC for Logback and Log4j. - Go: read the span context from
context.Context, or use theotelslogbridge from opentelemetry-go-contrib.
Once every record carries a trace ID, your backend can show the logs of a single request inside the trace view of distributed tracing and the trace behind any error log. Logs written outside a request (startup, cron jobs) simply have no trace context, which is fine.
Examples for Python, Node.js, Java and Go
Python: python-json-logger with OpenTelemetry correlation
import logging
from pythonjsonlogger.json import JsonFormatter # python-json-logger 3.x
from opentelemetry.instrumentation.logging import LoggingInstrumentor
LoggingInstrumentor().instrument() # adds otelTraceID / otelSpanID to records
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter(
"%(asctime)s %(levelname)s %(name)s %(message)s %(otelTraceID)s %(otelSpanID)s",
rename_fields={"levelname": "level", "otelTraceID": "trace_id", "otelSpanID": "span_id"},
))
logging.basicConfig(level=logging.INFO, handlers=[handler])
logging.getLogger("checkout").info("order placed", extra={"shop.order.id": "ord_8f3k2"})
structlog with structlog.processors.JSONRenderer() is an equally good choice; the Python integration page shows the full OpenTelemetry setup.
Node.js: pino with redaction
const pino = require('pino');
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
formatters: { level: (label) => ({ level: label }) },
redact: { paths: ['req.headers.authorization', '*.password'], censor: '[REDACTED]' },
});
logger.info({ 'shop.order.id': 'ord_8f3k2' }, 'order placed');
pino writes JSON by default. With @opentelemetry/instrumentation-pino registered, trace fields are added automatically.
Java: Logback with logstash-logback-encoder
<!-- logback.xml -->
<configuration>
<appender name="JSON" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
</appender>
<root level="INFO"><appender-ref ref="JSON"/></root>
</configuration>
The encoder includes MDC entries, so the trace_id and span_id set by the Java agent appear as JSON fields. Spring Boot 3.4 and later also support built-in structured output with logging.structured.format.console=ecs (or logstash, gelf).
Go: log/slog with trace context
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
func logWithTrace(ctx context.Context, msg string, args ...any) {
sc := trace.SpanContextFromContext(ctx) // go.opentelemetry.io/otel/trace
if sc.IsValid() {
args = append(args, "trace_id", sc.TraceID().String(), "span_id", sc.SpanID().String())
}
logger.InfoContext(ctx, msg, args...)
}
log/slog is part of the standard library since Go 1.21 and writes time, level and msg fields by default.
What not to log: secrets, PII and payloads
Logs are copied, shipped, indexed and kept for a long time, and many more people can read them than can read your production database. Treat them accordingly:
- Never log secrets: passwords, API keys, tokens, session cookies,
Authorizationheaders, private keys, connection strings with credentials. - Avoid personal data: names, email addresses, phone numbers, postal addresses, IP addresses where not needed, payment card data. Log an internal, pseudonymous ID instead.
- Do not dump full request or response bodies by default. They are the most common way personal data ends up in logs by accident.
- Be careful with exception messages from databases and HTTP clients; they sometimes include query parameters or URLs with tokens.
Use two layers of defense: redaction in the logger (like pino's redact) and PII masking in the pipeline before storage, because some service will eventually forget the first layer. Security and audit logs have their own rules for content and retention; our article on security logging and audit logs covers them.
Controlling log volume and cost in the pipeline
Log volume grows faster than traffic, because every new feature adds statements and nobody removes them. Instead of asking teams to delete logs during a cost crisis, control volume centrally in a telemetry pipeline such as the OpenTelemetry Collector:
- Filter by severity and source. Drop DEBUG records in production, health check noise and known chatty libraries.
- Sample high-volume INFO streams. Keep all WARN and ERROR records, but keep only a percentage of repetitive success logs. Sampling by trace ID keeps all logs of a sampled request together.
- Remove fields you never query and truncate oversized bodies.
- Route by value. Send audit logs to long retention, debug-level investigations to short retention.
An example Collector configuration (values are examples):
processors:
filter/drop-debug:
error_mode: ignore
log_conditions:
- log.severity_number < SEVERITY_NUMBER_INFO
transform/scrub:
error_mode: ignore
log_statements:
- delete_key(log.attributes, "password")
- replace_all_patterns(log.attributes, "value", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+", "<email>")
probabilistic_sampler/info:
sampling_percentage: 20
Newer Collector releases use log_conditions in the filter processor; the older logs: log_record: form is deprecated. Apply the sampler only to a pipeline that carries the high-volume INFO stream, not to errors. More patterns are in our guides to running the Collector in production and reducing observability costs pipeline-first.
Field reference and structured logging checklist
| Field | Example value | Required? |
|---|---|---|
timestamp | RFC 3339 in UTC, with milliseconds | Always |
level | INFO, WARN, ERROR | Always |
message | Short, constant text | Always |
service.name, service.version | checkout-api, 2026.10.4 | Always (resource) |
deployment.environment.name | production | Always (resource) |
trace_id, span_id | Lowercase hex | Inside requests |
http.route, http.response.status_code | /orders/{id}, 502 | For HTTP events |
exception.type, exception.stacktrace | TimeoutError, stack | For errors |
user.id or domain IDs | Pseudonymous ID | When relevant |
Structured logging checklist (copy into your code review template)
- One JSON object per line, written to stdout or a local file
- Field names follow OpenTelemetry semantic conventions; custom fields use a documented namespace
- Service name, version and environment set once as resource attributes
- Messages are short and constant; variable data goes into fields
- Levels follow the shared table; errors logged once where handled
- Log level configurable at runtime without a redeploy
- trace_id and span_id present on every record inside a request
- No secrets, tokens, credentials or full request bodies
- Personal data replaced by pseudonymous IDs; masking also enforced in the pipeline
- DEBUG dropped and high-volume INFO sampled in the pipeline, errors always kept
- Retention defined per log category
How Obseria helps with structured logging
Obseria is an OpenTelemetry-native observability platform, so JSON logs and OTLP log records from the libraries above arrive without a proprietary agent, and records with trace_id are linked to their traces automatically. Obseria Pipeline applies filtering, PII masking, sampling and routing before data is stored.
- Obseria Lake stores logs index-free in the EU, with usage-based pricing per signal and unlimited users.
- Logs, traces, metrics and errors of the same request are shown together.
- Obseria Intelligence uses correlated logs as evidence when it proposes a root cause.
You can send your first structured logs within minutes using a free Obseria trial.