Switching a service from plain text to JSON takes an afternoon. Getting value from it takes agreement: the same field names in every service, severity that means the same thing everywhere, and a trace ID on every line written inside a request. Without that, you have JSON that still needs a regex per team to query. These structured logging best practices are the conventions that make logs queryable across a whole system, with examples in Python, Go and Node.js and a look at how the OpenTelemetry logs bridge fits in.
What a structured log record should contain
Rather than invent a schema, start from the one OpenTelemetry already defined. The OpenTelemetry log data model describes every log record with a small set of top-level fields, and any backend that accepts OTLP understands them:
- Timestamp and ObservedTimestamp: when the event happened, and when the pipeline first saw it
- SeverityText and SeverityNumber: the level as written by the logger, and a normalized number for comparisons
- Body: the message itself
- Attributes: key-value pairs describing this event
- Resource: who emitted it, such as
service.name,service.versionanddeployment.environment.name - TraceId, SpanId and TraceFlags: the request this record belongs to
- InstrumentationScope: the logger or library that produced it
Even if you write JSON to stdout and never touch OTLP, shaping each line so that it maps onto this model costs nothing and saves a translation layer later. A line written inside a request might look like this:
{
"timestamp": "2026-11-17T09:12:44.183Z",
"level": "error",
"message": "payment declined",
"service.name": "checkout",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"span_id": "00f067aa0ba902b7",
"order.id": "ord_8f2k",
"payment.provider": "stripe",
"error.type": "card_declined",
"duration_ms": 412
}One event, one constant message
The message should name the event, not describe this particular occurrence of it. payment declined is the same string every time; Payment for order ord_8f2k declined after 412ms is unique on every call. Constant messages let you count events without a regex, group them in a pattern view, and compress well in a columnar store. Everything that varies goes into attributes.
A useful test: if you deleted every attribute, would the remaining messages still sort into a short, readable list of things your service does? If the answer is no, variables are leaking into messages.
Stable field names, borrowed from the semantic conventions
Field naming is where structured logging usually fails. One service writes userId, another user_id, a third uid, and a query across all three needs three clauses and someone who remembers all of them. Fix it once, with a written field dictionary, and take names from the OpenTelemetry semantic conventions wherever one exists:
http.request.method,http.routeandhttp.response.status_codefor HTTP contexturl.pathfor the request path (never the full URL with its query string; see below)error.typefor a short, low-cardinality error classexception.type,exception.messageandexception.stacktracefor caught exceptionsdb.system.nameanddb.operation.namefor database callsservice.nameandservice.versionas resource attributes, set once per process rather than per line
For your own fields, pick a scheme and write it down. Lowercase, dot-separated namespaces (order.id, payment.provider) match the conventions and read well. Put the unit in the name when a value has one (duration_ms, payload_bytes). Keep types stable: if http.response.status_code is an integer in one service and a string in another, numeric range queries break in ways nobody notices until an incident. And never put a variable in a key. cart_8f2k: true creates a new attribute key for every cart, which hurts query performance and storage in most backends.
Severity that maps cleanly
Every language spells levels differently. Python has WARNING and CRITICAL, pino uses numbers (30 for info, 50 for error), Go slog uses integers with gaps between them. OpenTelemetry normalizes all of these into SeverityNumber ranges, which is what you should filter and alert on:
- TRACE: 1 to 4
- DEBUG: 5 to 8
- INFO: 9 to 12
- WARN: 13 to 16
- ERROR: 17 to 20
- FATAL: 21 to 24
Keep the original text in SeverityText as well, so the line still reads the way the developer wrote it. In production, run at INFO, keep third-party library loggers at WARN, and make DEBUG switchable at runtime per service so turning it on during an incident does not need a deploy. The cost side of level discipline, including sampling debug logs by trace, is covered in cutting log management cost.
Put the trace ID on every line
A log line with a trace ID is a pointer into a request. From an error line you can open the trace and see every service the request touched, how long each step took, and which other log lines it produced. Without the ID, you are matching timestamps across services and hoping clocks agree.
For JSON logs that are not sent over OTLP, the OpenTelemetry trace context in non-OTLP log formats specification recommends the field names trace_id, span_id and trace_flags, with IDs as lowercase hex (32 characters for a trace ID, 16 for a span ID). Use exactly those names. Collector parsers and most backends look for them by default.
Examples in three languages
Python with structlog
structlog builds each record as a dict and passes it through a chain of processors, which makes it easy to add trace context and render JSON at the end:
import structlog
from opentelemetry import trace
def add_trace_context(logger, method_name, 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),
add_trace_context,
structlog.processors.dict_tracebacks,
structlog.processors.EventRenamer("message"),
structlog.processors.JSONRenderer(),
]
)
log = structlog.get_logger()
log.error("payment declined", **{"order.id": order_id, "error.type": "card_declined"})merge_contextvars picks up fields bound once per request with structlog.contextvars.bind_contextvars, so a handler does not repeat the order ID on every call. dict_tracebacks turns exceptions into structured data instead of a multi-line string that breaks line-based shippers. If you use the standard library logging module instead, the OpenTelemetry logging instrumentation can inject the same context; setup for both is on the Python monitoring page.
Go with log/slog
Since Go 1.21 the standard library ships log/slog with a JSON handler. Pass the request context to every call, and use LogValuer so sensitive types redact themselves wherever they are logged:
type Email string
// LogValue keeps the domain for debugging and drops the mailbox.
func (e Email) LogValue() slog.Value {
if _, domain, ok := strings.Cut(string(e), "@"); ok {
return slog.StringValue("***@" + domain)
}
return slog.StringValue("***")
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
logger.ErrorContext(ctx, "payment declined",
slog.String("order.id", orderID),
slog.String("error.type", "card_declined"),
slog.Any("customer.email", Email(email)),
)The JSON handler does not know about traces. To get trace correlation and OTLP export, swap in the OpenTelemetry bridge, go.opentelemetry.io/contrib/bridges/otelslog: otelslog.NewLogger("checkout") returns a *slog.Logger backed by the global LoggerProvider, and because the handler receives the ctx you pass to ErrorContext, the active span's IDs land on the record. Calls without a context get no trace ID, which is a good reason to make *Context methods the house rule.
Node.js with pino
pino writes JSON by default. Two settings are worth changing: emit the level as a label rather than a number, and declare redaction paths up front:
const pino = require("pino");
const logger = pino({
level: process.env.LOG_LEVEL || "info",
messageKey: "message",
formatters: {
level: (label) => ({ level: label }),
},
redact: {
paths: ["req.headers.authorization", "req.headers.cookie", "*.password"],
censor: "[REDACTED]",
},
});
logger.error({ "order.id": orderId, "error.type": "card_declined" }, "payment declined");With @opentelemetry/instrumentation-pino loaded (it is part of the Node auto-instrumentations bundle), records written inside an active span get trace_id, span_id and trace_flags fields added, and if a LoggerProvider is configured the same records are also sent to the OpenTelemetry Logs SDK. Both behaviors can be switched off independently with disableLogCorrelation and disableLogSending.
The OpenTelemetry logs bridge
OpenTelemetry deliberately does not ask you to replace your logger. Its Logs API exists for bridge authors: an appender or handler plugs into the logging library you already use and converts each record into an OpenTelemetry log record, with trace context taken from the active span. Java gets this through Logback and Log4j appenders (installed automatically by the Java agent), Go through otelslog and sibling bridges for zap and logrus, Node through the pino, winston and bunyan instrumentations. In Python the handler is moving out of the SDK: release 1.40.0 deprecated the SDK's LoggingHandler in favor of the opentelemetry-instrumentation-logging package, so check which one your version documents.
That leaves two ways to ship logs, and both are fine:
- OTLP from the process. The bridge exports records directly, with severity, attributes and trace context already in the right fields. No parsing, no file handling.
- JSON to stdout, collected from files. The process writes JSON lines and an OpenTelemetry Collector running as a node agent tails them with the
filelogreceiver. Container logs survive a crashed process and the application has no export dependency.
If you take the file route, parse the JSON and promote timestamp, severity and trace fields into the data model in one operator, so that records arrive looking as if they came over OTLP:
receivers:
filelog:
include: [/var/log/pods/*/*/*.log]
operators:
- type: container
- type: json_parser
timestamp:
parse_from: attributes.timestamp
layout_type: gotime
layout: "2006-01-02T15:04:05.999999999Z07:00"
severity:
parse_from: attributes.level
trace:
trace_id:
parse_from: attributes.trace_id
span_id:
parse_from: attributes.span_idWithout the severity block, file-tailed records arrive with severity 0 (unspecified), and any filter written as "drop everything below INFO" silently removes them. Which route to choose depends on how you run Collectors generally; the tradeoffs are in Collector vs direct SDK export.
What not to log
Structured logs make it easy to log too much, because logger.info("request", req=request) is one line and serializes everything. Leave these out by default:
- Credentials:
Authorizationheaders, cookies, API keys, session and refresh tokens, signed URLs - Bodies: full request and response payloads; log their size and content type instead
- Personal data you do not need: email addresses, names, phone numbers, street addresses, payment details. Log a stable internal user ID, or a keyed hash of one, when you only need to correlate
- Whole objects: a serialized ORM model or config struct includes whatever fields get added next year
- Query strings and raw SQL with literals: both regularly carry tokens and personal data
- Stack traces on every retry: log the full trace once, when the operation finally fails
Prefer allowlists to blocklists. A function that logs the five fields of a request you chose survives a refactor; a redaction list that strips the fields you remembered does not. Redaction in the logger configuration (pino's redact, slog's LogValuer) and in the pipeline are safety nets behind that, not substitutes for it.
Test the log schema like an API
Dashboards, alerts and saved queries depend on field names, so a renamed field is a breaking change that no compiler catches. Write a test for the events that matter. structlog ships structlog.testing.capture_logs() for exactly this:
from structlog.testing import capture_logs
def test_declined_payment_is_logged_with_schema():
with capture_logs() as logs:
charge(order_id="ord_1", card=DECLINED_CARD)
event = next(e for e in logs if e["event"] == "payment declined")
assert event["log_level"] == "error"
assert event["order.id"] == "ord_1"
assert event["error.type"] == "card_declined"
assert "card.number" not in eventThe last assertion matters as much as the others: a test that proves a sensitive field is absent stops it from coming back. In Go, point a slog.NewJSONHandler at a bytes.Buffer and decode the output in the test; in Node, pass pino a writable stream that collects lines.
A checklist
- One JSON object per line, shaped to map onto the OpenTelemetry log data model
- Constant messages that name the event; everything variable in attributes
- A written field dictionary that reuses semantic convention names, with units in names and stable types
- Severity mapped to
SeverityNumber, INFO in production, DEBUG switchable at runtime trace_idandspan_idon every line written inside a request- Credentials, bodies and unneeded personal data never logged; allowlists over blocklists
- Severity and trace fields promoted at parse time if logs are collected from files
- Tests that pin the schema of important events, including fields that must not appear
Structured logs in aiAxonIQ
Everything above is standard OpenTelemetry and works with any OTLP backend. aiAxonIQ Log Management ingests over OTLP, syslog, FluentBit, Vector and Logstash, extracts attributes from JSON on read, and stores records in per-tenant OpenObserve streams, where full-text search runs over the same copy. Logs that carry a trace ID link to the correlated span in one click, live tail follows a deploy across services, and automated pattern clustering groups constant messages into templates, which is where the one-event-one-message rule pays off. Runtime parameter masking for sensitive tokens and personal data adds a further safety net behind the redaction you do at the source.