What Is Structured Logging in OpenTelemetry?
Structured logging means writing log records as organized, labeled data instead of loose sentences, so that machines can search, filter, and connect them to traces. This guide explains from zero how OpenTelemetry models logs, how structured logs travel through your system, and how to use them well.
Imagine two ways of keeping a diary for a busy restaurant. In the first, the manager scribbles whatever comes to mind in a notebook: “Table nine was angry about the soup again, I think around eight.” In the second, the manager fills in a printed form for every event, with boxes for the time, the table number, the type of problem, the dish involved, and how serious it was. A week later, someone asks how many soup complaints happened on busy evenings. With the notebook, a person must read every page and guess. With the forms, the answer takes seconds. Structured logging is the printed form. It turns the diary of your software from a pile of sentences into data that can be questioned, and OpenTelemetry gives that data a standard shape.
1The Big Picture: Why Logs Still Matter
Logs are the oldest form of telemetry, and they remain the most detailed.
Every program ever written has needed a way to tell its owners what it is doing. The simplest way is to write a line of text whenever something noteworthy happens: a user signed in, a payment failed, a file could not be opened. These lines are called logs. Long before the words observability and tracing became popular, engineers solved problems by reading logs, and they still do, because logs capture the specific details of individual events that no summary can hold.
OpenTelemetry, often shortened to OTel, is an open-source, vendor-neutral standard for creating and moving telemetry. It covers three main kinds of data, called signals. Traces follow a request across services. Metrics summarize behavior as numbers over time. Logs record individual events with their details. Each signal answers a different kind of question, and the real power appears when all three are connected.
Traces
Show the path and timing of a single request through many services.
Metrics
Summarize behavior as numbers over time, such as error rates and response times.
Logs
Record individual events with rich detail, such as exactly which payment failed and why.
Think of investigating a delivery that arrived late. Metrics are the statistics: ten percent of deliveries were late this week. A trace is the tracking history of this one parcel, showing every depot it passed. The log is the driver’s note at one particular stop: “Gate locked, waited twenty minutes for the caretaker.” You often need all three to understand what truly happened.
The Problem with Logs as They Are Usually Written
Traditional logs are written for humans to read, one line at a time. That works while one person reads one file on one machine. It breaks down when you run dozens of services across hundreds of machines producing millions of lines per hour. Nobody can read that much, so you must search it with tools, and tools struggle with free-form sentences. Structured logging is the solution to that struggle.
OpenTelemetry does not replace your existing logging habits overnight. It gives logs a standard shape and a standard way to travel, and it lets you connect them to traces and metrics. You can adopt it gradually.
2What Is a Log, and What Goes Wrong with Plain Text?
Before improving logs, we need to see why plain text logs cause pain.
A log record is a single entry that says something happened at a certain time. In its simplest form, it is one line of text beginning with a time, followed by a severity word such as information or error, followed by a human-readable sentence. For example, a line might say that a user with a particular name logged in from a particular address at a particular time. A person reads it easily. A computer sees only a string of characters.
Why Plain Text Becomes Painful
Hard to Search Precisely
To find all failures for one customer, you must search for text and hope the customer’s name always appears in the same wording.
Inconsistent Wording
Different developers phrase the same event differently, so one search never finds them all.
Fragile Parsing
Tools that extract values from sentences rely on patterns that break whenever someone rewords a message.
Hard to Count and Group
Questions like “how many failures per region” need real fields, not sentences.
Multi-Line Confusion
Error stack traces span many lines, and tools may split one event into many unrelated records.
No Link to Traces
Without an identifier connecting a line to a request, you cannot easily see which request produced it.
Searching plain text logs is like searching a stack of handwritten letters for every mention of a certain person, when some letters call them by their full name, some by a nickname, and some only by “he”. You will miss some and read many irrelevant ones. A form with a “name” box would have made it trivial.
Assuming that more detailed sentences solve the problem. A longer sentence is still a sentence. The fix is not more words but better organization of the facts inside the record.
3What Is Structured Logging?
Structured logging records each event as a set of named fields rather than a free-form sentence.
Structured logging is the practice of writing each log record as organized data with named fields, instead of a single sentence of free text. A structured record still has a short human-readable message, but the important facts, such as the customer, the region, the amount, and the error type, are stored as separate labeled values. Because each fact has a name, tools can read them reliably without guessing.
Often, structured logs are written in a text format designed for data, with names and values paired up. But the format is not the point. The point is that the record has a stable shape that machines can understand. In OpenTelemetry, this shape is defined formally as the log data model, which we will explore soon.
A hospital admission form is structured: it has boxes for name, age, symptoms, and allergies. A doctor’s rambling voice memo is unstructured. Both contain information, but only the form lets the hospital quickly find every patient with a particular allergy. Structured logging gives your software’s diary the form treatment.
The Two Layers of a Structured Log
A useful way to think about a structured record is as two layers. The first is a short, stable description of what happened, such as “payment failed”. The second is the set of facts that vary from event to event, such as which customer, which amount, and which provider. Keeping the description stable and the variable facts in separate fields is the heart of good structured logging, and it makes similar events easy to group.
What Makes a Good Structured Log?
A good structured log record has several qualities. It describes one thing that happened, rather than bundling many events together. It carries a clear, stable message that a stranger could understand. It includes the facts someone is likely to search for, each in its own named field. It states its severity honestly. And it is safe, meaning it contains no secrets or private personal information. When a record fails any of these tests, it is better rewritten than kept.
It also helps to remember the audience. Logs are not written only for the author. They are read by on-call engineers in the middle of the night, by support staff investigating a complaint, and by analysts studying trends. Clear names and values that a stranger can understand are far more valuable than clever shorthand that only the original developer remembers.
Structured does not mean unreadable by humans. Good tools display the fields neatly, and the short message still tells a human what happened at a glance.
4Unstructured, Semi-Structured, and Structured Logs
Logs sit on a spectrum, and most real systems have a mixture.
It helps to see logs as a spectrum rather than two boxes. At one end are completely free-form lines. At the other end are records with a strict, shared shape. In between are lines that follow a loose pattern, which tools can sometimes parse with rules, but not reliably.
| Style | What it looks like | How tools read it | Reliability |
|---|---|---|---|
| Unstructured | A free-form sentence written by a developer | Text search only | Low |
| Semi-structured | A consistent line pattern, such as time, level, then message | Parsing rules that match the pattern | Medium; breaks when wording changes |
| Structured | Named fields with values, in a stable shape | Direct field access | High |
flowchart LR
A["Unstructured text line"] -->|"parsing rules"| B["Semi-structured pattern"]
B -->|"extract fields"| C["Structured record"]
D["Structured from the start"] --> C
Why Structure at the Source Is Best
You can convert unstructured lines into structured records later, using parsing rules in a processing tool. This is a very useful rescue technique for old software you cannot change. But every parsing rule is a guess about wording, and any change in the original sentence can silently break it. Writing structured records at the source avoids the guessing entirely, because the developer states exactly which value belongs in which field.
Use parsing as a bridge for legacy systems, and structured logging at the source for everything new. Over time, the bridge carries less and less traffic.
5The OpenTelemetry Log Data Model
OpenTelemetry defines exactly which fields a log record has, so every tool agrees.
One of the most valuable things OpenTelemetry offers is a shared definition of what a log record looks like. This definition is called the log data model. Because every logging library, Collector, and backend that follows the standard agrees on these fields, a record created in one language can be understood by a tool written in another, without special translation.
Timestamp
When the event happened, according to the source that created it.
Observed Timestamp
When the record was noticed by the collection system. Useful when the original time is missing or inaccurate.
Trace ID and Span ID
Identifiers linking the log to the trace and operation that were active when it was written.
Severity
How serious the event is, stored as both a readable name and a number.
Body
The main content of the record: usually the message, but it can itself be structured data.
Attributes
Named facts about this particular event, such as the customer tier or the error type.
Resource
Describes the thing that produced the log: the service name, version, host, and environment.
Instrumentation Scope
Identifies the library or component that emitted the record.
flowchart TD
L["Log record"] --> T["Timing: timestamp, observed timestamp"]
L --> C["Correlation: trace ID, span ID"]
L --> S["Severity: name and number"]
L --> B["Body: the message or data"]
L --> A["Attributes: facts about this event"]
L --> R["Resource and scope: who produced it"]
Why Two Timestamps?
The first timestamp says when the event happened. The second says when the collection system saw it. Usually they are almost identical. But when logs are read from files, the original time may be missing, written in an odd format, or recorded by a machine with a wrong clock. Keeping both lets tools be honest about what they know and prevents silent confusion.
Notice how similar this is to a span. Resource, scope, attributes, and identifiers are shared ideas across signals. Learn them once and they help you everywhere in OpenTelemetry.
6Severity: How Serious Is This Event?
Severity helps you separate routine chatter from real trouble.
Every log record can carry a severity, which says how important or alarming it is. Different logging libraries use different words: some say warning, others say warn, some have a level called critical and others call it fatal. To end this confusion, OpenTelemetry defines a numbered scale from one to twenty-four, grouped into six bands. Every library’s levels are mapped onto this scale, so tools can compare logs from any source.
| Band | Numbers | Meaning | Typical use |
|---|---|---|---|
| Trace | 1 to 4 | Extremely fine detail | Step-by-step internals while debugging |
| Debug | 5 to 8 | Detail useful to developers | Values and decisions during development |
| Info | 9 to 12 | Normal, noteworthy events | A user signed in; a job finished |
| Warn | 13 to 16 | Something unusual that is not yet a failure | A retry was needed; a limit is near |
| Error | 17 to 20 | An operation failed | A payment could not be processed |
| Fatal | 21 to 24 | The program cannot continue | A critical resource is gone and the service must stop |
Why Both a Name and a Number?
The severity text keeps the original wording from the source library, which is helpful for people reading the logs. The severity number gives tools a single, comparable scale. A rule such as “keep everything at warn or above” is a simple numeric comparison that works for logs from every language. The bands also leave room within each band, so a library with several levels of debug detail can map them to different numbers inside the debug band.
Severity is like the color coding at a hospital emergency room. Green patients can wait, yellow need attention soon, and red need help now. A shared color scale lets every nurse in every ward understand urgency instantly, without learning each ward’s private terms.
Labeling everything as error “to make sure someone notices”. When every line screams, nobody listens. Reserve error for real failures so that alerts based on severity stay meaningful.
7Body and Attributes: Where to Put What
The heart of structured logging is deciding which facts go in the message and which go in fields.
A log record has two places for information about the event: the body and the attributes. Understanding the difference is the single most important skill in structured logging.
The Body
The body is the main content of the record. For most application logs, it is a short human-readable message such as “payment failed” or “order shipped”. In OpenTelemetry the body is flexible: it can be simple text, but it can also be structured data itself, such as a collection of named values. This flexibility exists so that existing logs of many shapes can be carried faithfully. For application logging, the common and recommended pattern is a clear, stable message in the body.
The Attributes
Attributes are the named facts about this particular event. The customer’s plan tier, the region, the order amount, the error type, and the name of the payment provider are all attributes. Each has a key and a value, using the same attribute system you meet on spans and metrics. Because each fact has its own field, tools can filter on it, count by it, and compare it across thousands of records.
| Put it in… | When the information is… | Example |
|---|---|---|
| Body | A stable, readable description of what happened | Payment failed |
| Attributes | A variable fact you may want to search, count, or group by | Provider name, region, amount, error type |
| Resource | A fact about the producing service, constant for its lifetime | Service name, version, environment |
The Stable Message Idea
A powerful habit is to keep the message constant for a given kind of event and move every changing detail into attributes. Compare two ways of logging a failed payment. In the first, the message is built by pasting details into a sentence, so every record has different text. In the second, the message always says the same thing, and the details live in fields. With the second approach, you can find every payment failure by searching for one message, and you can break them down by provider or region instantly.
Think of an email subject line and the form fields in a support ticket. The subject, “Refund request”, is the same for all such tickets. The order number, the amount, and the reason are separate fields. Support staff can list all refund requests and sort by amount, because the subject stayed constant and the details lived in fields.
Building messages by gluing variable details into the sentence. It looks friendly to a human reading one line, but it destroys grouping and searching for everyone else.
8Resource, Scope, and Semantic Conventions for Logs
Shared names for common facts keep logs consistent across services.
Just as with traces and metrics, OpenTelemetry has semantic conventions for logs: a published, community-maintained dictionary of standard attribute names for common situations. If every team names the same idea differently, searching across services becomes impossible. A shared dictionary solves this, and tools that understand the dictionary can offer helpful features automatically.
Resource Attributes on Logs
Every log record is associated with a resource that describes who produced it. The service name, the service version, the deployment environment, the host, and in container platforms the pod and namespace are typical resource facts. They are recorded once for the source rather than repeated on every record, and backends combine them with the record when you search. Having consistent resource attributes across logs, traces, and metrics is what lets you jump between signals for the same service.
| Area | Example attribute | What it tells you |
|---|---|---|
| Service identity | service.name | Which service produced the record |
| Service version | service.version | Which release was running |
| Errors | exception.type | The kind of error that occurred |
| Errors | exception.message | The error’s message text |
| Errors | exception.stacktrace | The call history leading to the error |
| File-based logs | log.file.path | The file the record was read from |
Naming Your Own Attributes
For facts specific to your business, create your own attributes while following the same style as the standard ones. Use lowercase, use dots to group related names, use underscores between words, and begin custom names with a prefix for your organization or application so they never collide with future standard names. Check the standard dictionary first, because reusing a standard name gives you free tool support.
Write down your team’s custom attribute names and meanings in one shared place. It prevents duplicates such as customer_id, customerId, and cust.id all meaning the same thing.
Renaming an attribute silently breaks every saved search and alert that used the old name. Treat attribute names as a public contract.
9The Superpower: Correlating Logs with Traces
A log that knows which request it belongs to becomes far more valuable.
The most exciting benefit of structured logging in OpenTelemetry is correlation. A trace is the story of one request, identified by a trace identifier, and each operation inside it has a span identifier. If a log record carries those two identifiers, you can jump from any log line directly to the trace that produced it, and from any span to every log written during it.
The remarkable part is that this usually happens automatically. When your application writes a log while a span is active, the OpenTelemetry logging integration reads the current trace and span identifiers from the surrounding context and attaches them to the record. The developer does not have to remember to include them or copy them by hand.
flowchart LR
A["Request arrives"] --> B["Span starts: trace ID and span ID created"]
B --> C["Application writes a log"]
C --> D["Log record gets the same trace ID and span ID"]
D --> E["Backend links the log to the trace"]
Imagine every note a hospital staff member writes about a patient automatically carries the patient’s wristband number. Years later, you can gather every note about one patient in seconds, even if the notes were written by different people in different wards. The trace identifier is the wristband number for a request.
What This Makes Possible
From a Slow Trace to Its Logs
You notice that one span in a trace took far too long. With one click you see every log written during that span, and a warning about a retry explains the delay immediately.
From an Error Log to the Whole Story
You find an error log and wonder what the user was doing. The trace identifier opens the full request path, showing which services were involved before the failure.
One Search Across All Services
Searching for one trace identifier returns the logs from every service that touched the request, in time order. A bug that crosses five services becomes one easy-to-read timeline.
Correlation depends on the log being written while a span is active. Logs from background work with no active trace will simply have no identifiers, which is normal.
10How Applications Emit Logs: The Bridge and the SDK
You usually keep using your existing logging library; OpenTelemetry connects to it.
Developers often ask whether they must learn a brand-new logging interface. The answer is usually no. Most languages already have well-loved logging libraries, and teams have years of habits built around them. OpenTelemetry respects this. Instead of asking you to rewrite your logging calls, it provides a logs bridge that connects your existing library to the OpenTelemetry system.
The Moving Parts
Your Existing Logging Library
Your code keeps writing logs the way it always has, using the library your team already knows.
The Bridge or Appender
A small adapter attached to your logging library receives each record and converts it into the OpenTelemetry log record shape, adding trace context when available.
The OpenTelemetry Logs SDK
The SDK attaches the resource, applies any configured processing, and hands the records to an exporter.
Batching and Export
Records are collected into batches and sent out, typically in the OpenTelemetry protocol, to a Collector or directly to a backend.
The logs API in OpenTelemetry is mainly intended for people who build bridges and appenders for logging libraries, not for everyday application developers. Application developers normally keep calling their usual logger.
Batching and Reliability
Sending every log record across the network immediately would slow the application and waste bandwidth. For that reason, the SDK normally places records in a buffer and sends them in batches at regular intervals, or when the buffer fills. This is efficient, but it means that if the application crashes suddenly, the most recent records still sitting in the buffer may be lost. Good configurations flush the buffer when the application shuts down normally, and keep the buffer size and interval at sensible values. If you cannot afford to lose even the last few records, writing to a file that a Collector reads can be a more forgiving approach.
Why a Bridge Is a Smart Design
This design gives you the best of both worlds. Your developers keep a familiar tool and do not need to change thousands of logging calls. Meanwhile, every record gains the standard OpenTelemetry shape, the shared resource information, and the automatic trace correlation. It also means you can switch backends without touching application code, because the destination is decided by configuration.
The bridge is like a universal travel adapter. Your appliance keeps its original plug and works as before, but the adapter lets it connect to any wall socket in any country. Your logging library keeps its original interface, and the bridge lets it plug into the OpenTelemetry system.
Structured at the Source with Existing Libraries
Most modern logging libraries already support attaching named values to a log call, rather than only a message. When you use that feature, the bridge carries those named values into the record’s attributes. This is the cleanest way to get structured logs: use your library’s structured features, and let the bridge deliver them.
11Two Paths: Direct Export or Files and the Collector
There are two common ways for logs to leave your application, each with different trade-offs.
Logs can reach the Collector or backend in two broad ways. In the first, the application sends records directly using the OpenTelemetry SDK and bridge. In the second, the application simply writes structured lines to standard output or to a file, and a Collector running nearby reads them and converts them into OpenTelemetry records. Many organizations use both for different parts of their systems.
flowchart LR
subgraph PathA
A1["Application with bridge"] -->|"OTLP"| C1["Collector"]
end
subgraph PathB
A2["Application writes to output or file"] --> F["Log file"]
F -->|"read by file log receiver"| C2["Collector"]
end
C1 --> BE["Backend"]
C2 --> BE
| Aspect | Direct export from the application | Files read by a Collector |
|---|---|---|
| Trace correlation | Automatic, using active context | Works only if the application writes the identifiers into the file |
| Application changes | Add the bridge and configuration | Often none; works for legacy software |
| If the network or Collector is down | Depends on buffering in the SDK | The file keeps the logs until they can be read |
| Parsing needed | Not needed; records are already structured | Needed unless the lines are already structured |
| Best fit | New services you control | Containers, legacy systems, third-party software |
Why the File Path Is So Popular
In container platforms, the standard habit is for each application to write logs to standard output, and the platform stores them as files on the machine. A Collector running on each machine then reads those files. This approach is simple, requires no network setup in the application, and means that a crash does not lose logs that were already written. Its main weakness is that parsing and correlation must be handled with care, which is much easier if the lines were structured to begin with.
If you choose the file path, write each log as one self-contained structured line that includes the trace and span identifiers. You keep most of the benefits of direct export with none of the parsing guesswork.
12The Collector: Parsing, Enriching, Filtering, and Protecting Logs
The Collector is the workshop where logs are cleaned up before they reach storage.
The OpenTelemetry Collector is a standalone program that receives telemetry, processes it, and sends it onward. For logs, it can do a lot of useful work in the middle. Because it is central, a fix made in the Collector benefits every service at once, without redeploying any application.
Receive Logs
Accept records over the OpenTelemetry protocol, read files, accept syslog messages, or read from message queues.
Parse into Structure
Turn unstructured or semi-structured lines into proper fields using parsing rules, rescuing legacy logs.
Enrich
Add context such as environment, region, or Kubernetes details so every record carries consistent labels.
Normalize
Rename fields and map different severity words onto the standard scale so logs from all sources look alike.
Filter
Drop noisy records, such as low-severity debug lines or health checks, to save cost.
Redact
Remove or mask sensitive values before logs leave your network.
Receivers and Processors for Logs
On the receiving side, the file log receiver reads files and can apply parsing steps as lines are read. Other receivers handle syslog, system journals, message queues, and the standard OpenTelemetry protocol. On the processing side, general-purpose processors can add, rename, and delete attributes, a more flexible transform processor can change records based on conditions, a filter processor can drop records, and a batching processor groups records for efficient sending. The Collector can also route different logs to different destinations.
The Collector is a mailroom. Letters arrive in many formats. Staff open them, copy key details into a standard form, add the department stamp, throw away junk mail, and black out private details before sending the letters on. Senders do not need to know any of it happens.
Relying forever on parsing rules for software you control. Every rule is a guess about wording. Where you can change the software, make it write structured logs and retire the rule.
13Events and Exceptions: Structured Logs with Meaning
Some log records represent well-defined happenings, and OpenTelemetry gives them a name.
Ordinary log records are loosely defined: a developer writes whatever seems useful. But some happenings are important enough to define precisely, such as “a user clicked a button” or “a page finished loading”. OpenTelemetry treats these as events, which are log records that carry an event name and follow an agreed set of attributes for that kind of happening.
Giving events names and standard fields means every tool can recognize them and analyze them consistently. A browser-monitoring tool and a server-side tool could both understand the same kind of event, because they agree on its name and its fields.
Recording Errors Well
Errors are the most common reason people read logs, so recording them well matters. The standard approach uses dedicated attributes for the error type, the error message, and the stack trace. Because these have standard names, tools can group similar errors together, count how often each type occurs, and show the stack trace neatly formatted, even when logs come from services written in different languages.
Grouping by Error Type
A team notices a spike in failures. Grouping by the standard error-type attribute shows that nearly all of them are timeouts calling one dependency. Without a consistent field, the team would have read hundreds of differently worded messages.
Stack Traces as Data
Because the stack trace is stored in its own field rather than spread across many lines of text, it stays attached to the record that caused it and does not get split into unrelated pieces by file readers.
Errors can also be recorded as events on a span, which keeps them inside the trace. Many teams do both: an error event on the span and an error log, linked by the same identifiers.
14Searching and Analyzing Structured Logs
Structure turns log searching from reading into asking questions.
The payoff of structured logging is felt when you sit in front of a log search screen during an incident. With structured fields, you can ask precise questions and get precise answers. Most tools let you do four things.
Filter
Show only records matching a condition, such as errors from one service in the last hour for one region.
Group and Count
Count records by a field, such as errors per error type or per customer plan, to see which category dominates.
Compare
Look at how counts differ between versions, regions, or time periods to spot what changed.
Follow
Use the trace identifier to follow one request across every service that logged about it.
A Payment Failure Investigation
Support reports failed payments. An engineer filters for error-level records with the stable payment-failed message, groups by provider, and sees that one provider accounts for almost every failure. A single trace identifier shows the request path, confirming the provider’s service timed out.
A Release Comparison
After a new version is deployed, warnings rise slightly. Grouping by the service-version resource attribute shows that all the new warnings come from the new version, and the team decides to roll back before customers notice.
Logs as a Source of Metrics
Once logs are structured, counting them becomes easy, so some teams derive metrics from them, such as errors per minute by type. This is convenient, but remember that counting at the source with proper metrics is usually cheaper and more reliable than counting logs after the fact. Use logs for detail and metrics for ongoing trends.
When deciding which attributes to record, imagine the questions you will ask during an outage. Each question that begins with “is it only…” points to a field worth having.
15Volume, Cost, and Retention
Logs are usually the largest and most expensive signal, so manage them deliberately.
Logs tend to be the highest-volume signal in a system. A busy service can write thousands of lines every second, and every line has a cost: processing in the application, network bandwidth, storage, and indexing so it can be searched. Structured logs carry field names and values, which can make each record somewhat larger than a plain sentence, but the extra size usually pays for itself in searchability.
Controlling Volume
Choose Severity Wisely
Run production at information or warning level, and keep debug detail off unless you are investigating.
Filter in the Collector
Drop noisy, low-value records such as health checks before they reach expensive storage.
Avoid Logging in Tight Loops
A line written for every item in a huge loop can produce millions of records from one operation.
Keep Values Small
Avoid attaching huge payloads. Log identifiers and summaries instead of entire documents.
Tier Your Retention
Keep recent logs searchable and older ones in cheaper storage, and delete data you no longer need.
Prefer Metrics for Counting
If you only need a number over time, record a metric rather than logging every event.
Think of a warehouse. Storing every scrap of paper that ever arrived would fill the building and make finding anything impossible. A sensible warehouse keeps recent, valuable items close to the door, moves older items to the back, and discards what is no longer needed. Log retention works the same way.
Logs and Trace Sampling
Traces are often sampled, meaning only a fraction are kept. Logs are normally not sampled in the same way, so you may see a log carrying a trace identifier for a trace that was not stored. That is expected, not a fault. The log is still valid and still useful; the identifier simply points to a trace that was not kept.
Turning on the most detailed level everywhere “just in case”. The resulting flood of records can slow applications, overload the pipeline, and produce a surprising bill.
16Security and Privacy in Logs
Logs are written by developers, read by many people, and kept for a long time, so they can leak secrets.
Logs are one of the most common places where sensitive information leaks by accident. A developer logs an entire request to help debugging, and it contains a password or a payment card number. Another logs a database statement with a real email address inside. Because logs are widely accessible and stored for months, the damage can be large and lasting. Structured logging helps here, because it lets you control precisely which fields are recorded, but it does not remove the risk by itself.
Secrets
Passwords, access tokens, API keys, and session identifiers must not appear in logs.
Payment Details
Card numbers and bank information are heavily regulated and have no place in logs.
Personal Data
Names, emails, phone numbers, and precise locations may be regulated. Prefer opaque identifiers.
Whole Payloads
Complete request bodies and raw statements often hide sensitive values in unexpected places.
Layers of Protection
The strongest approach has several layers. First, design what gets logged so that sensitive values are never included. Second, use a clear allow-list of fields for sensitive areas of the code. Third, use the Collector as a safety net, with redaction, masking, and deletion rules that catch mistakes before logs leave your network. Fourth, restrict who can read logs in the backend, and set sensible retention so old data does not linger.
Removing a sensitive value after it has been stored is far harder than never recording it. Prevention at the source plus a Collector safety net gives the best protection.
17Real-World Examples
Seeing structured logging in familiar situations makes the ideas concrete.
An Online Shop
Each order service log has a stable message, the severity, the order’s sales channel, the payment method, and the customer plan tier as attributes, along with the trace identifiers. When a customer reports a failed order, support finds the exact record in seconds and engineers open the full trace.
A Legacy Application
An older application writes plain text lines to a file and cannot be changed. A Collector reads the file, applies parsing rules to extract time, severity, and key values, and adds resource information. The old system gains structure without a single code change.
A Kubernetes Platform
Every application writes structured lines to standard output. A Collector on each node reads the container log files and enriches each record with pod, namespace, and cluster details. Developers focus on their code while the platform handles collection.
A Microservice Incident
A checkout request fails across five services. Searching by the trace identifier shows every log from every service in time order, revealing that the inventory service logged a warning about a timeout before the payment service returned an error.
A Compliance Requirement
A company must prove that certain sensitive actions were recorded. Structured audit events with fixed fields for who, what, and when make audits straightforward, because auditors can query exact fields rather than interpret sentences.
A Cost Reduction Project
A team discovers that health-check lines make up a large share of their log volume. A Collector filter drops them, and a severity policy keeps debug detail off in production. Storage cost falls noticeably while incident response remains just as effective.
18Advantages and Trade-offs
Structured logging is one of the highest-value habits in observability, but it takes discipline.
Advantages
- Precise search and filtering on any field instead of guessing at wording.
- Easy counting, grouping, and comparison across services and versions.
- Automatic correlation with traces through shared identifiers.
- One standard shape that every tool and language can understand.
- Existing logging libraries can be reused through bridges.
- Centralized cleaning, enrichment, and redaction in the Collector.
Disadvantages / Trade-offs
- Teams must agree on field names and keep them consistent.
- Records can be larger than plain text, raising storage cost.
- Raw structured lines can be harder for humans to read without a good viewer.
- Sensitive data can still leak if fields are chosen carelessly.
- Converting legacy logs requires parsing rules that can break.
Who Benefits from Better Logs?
Structured logs help far more people than the developers who write them. On-call engineers resolve incidents faster because they can filter precisely instead of reading walls of text. Support teams answer customer questions quickly by finding the exact record for a given order or request. Security teams look for unusual patterns, such as repeated failed sign-ins from one network. Product teams study how features are used. Auditors check that important actions were recorded with the right details. Because so many groups rely on the same logs, a small investment in consistent structure pays back many times over across the organization.
A Simple Adoption Path
You do not need to change everything at once. A gentle path starts by switching new code to your logging library’s structured features and a stable message style. Next, add the OpenTelemetry bridge so records carry the standard shape and trace identifiers. Then set consistent resource attributes across logs, traces, and metrics. After that, use the Collector to parse legacy logs, filter noise, and redact sensitive values. Finally, agree on a shared dictionary of attribute names and review it from time to time. Each step delivers value on its own.
Before adding a field to a log record, name the search or chart that will use it. If you cannot, the field probably adds cost without value.
19Best Practices and Common Mistakes
A handful of habits prevent most problems.
Habits Worth Building
Stable Messages
Keep the message constant for each kind of event and move variable details into attributes.
Use Standard Names
Reuse semantic conventions so tools understand your fields automatically.
Include Trace Context
Let the bridge attach trace and span identifiers so logs connect to traces.
Choose Severity Honestly
Reserve error for real failures so severity-based alerts stay meaningful.
Protect Sensitive Data
Never log secrets, and add Collector redaction as a safety net.
Control Volume
Filter noise, avoid logging in tight loops, and keep production severity sensible.
Mistakes to Avoid
Problem
Developers build messages by pasting variable details into sentences, so every record has different wording and the real facts are buried in text.
Why It’s Harmful
Searching, grouping, and counting become unreliable. Teams fall back on fragile text patterns that break whenever someone rewords a message.
Correct Approach
Use a stable message for each kind of event and record the changing facts as named attributes, so records group naturally and can be filtered precisely.
Problem
Whole request bodies, full database statements, tokens, or personal details are written into logs to make debugging easier.
Why It’s Harmful
Sensitive data spreads to every system that stores or reads logs and stays for as long as logs are retained, creating security and legal risk.
Correct Approach
Log only the specific safe fields you need, prefer opaque identifiers, and configure redaction in the Collector as a second line of defense.
Problem
Every team invents its own field names, with mixed capitalization, for the same ideas, and detailed debug logging is left on everywhere.
Why It’s Harmful
Searches miss records, cross-service analysis needs endless special cases, and log volume and cost grow far faster than the value gained.
Correct Approach
Agree on a shared naming guide, reuse standard conventions, and set clear severity and volume policies, adjusting temporarily only when investigating.
Treating logs as a dumping ground. Unused fields and noisy lines cost money and attention. Be selective and intentional about what you record.
20Frequently Asked Questions
Quick answers to the questions beginners ask most often.
A plain log is a sentence of free text. A structured log stores the important facts as separate named fields, so tools can search, filter, and count by those fields reliably.
Usually not. OpenTelemetry provides bridges or appenders that connect existing logging libraries to its system, so developers keep their familiar tools while records gain the standard shape.
The body is the main content, usually a short stable message. Attributes are named facts about this particular event, such as the region or error type. Keep the message stable and put variable details in attributes.
When a log is written while a span is active, the trace and span identifiers are attached to the record. A backend can then link the log to the trace, and the trace back to its logs.
OpenTelemetry maps every library’s levels onto a shared numeric scale from one to twenty-four, grouped into trace, debug, info, warn, error, and fatal bands, so logs from any source can be compared.
Yes. A Collector can read the software’s log files or syslog output, parse the lines into fields, and add resource information, giving legacy logs structure without code changes.
Both are valid. Direct export gives automatic trace correlation and no parsing. Files read by a Collector suit containers and legacy systems and survive short outages. Many organizations use both for different services.
Not normally. Logs are usually kept or filtered by severity and rules rather than sampled by trace. A log may therefore point to a trace that was not stored, which is expected.
An event is a log record that carries a name and follows an agreed set of attributes for a specific kind of happening, which lets tools recognize and analyze it consistently.
Design logging so that secrets and personal data are never recorded, prefer opaque identifiers, and add redaction and deletion rules in the Collector as a safety net. Also restrict access to logs and set sensible retention.
21Summary and Key Takeaways
Structured logging means recording each event as a set of named fields rather than a loose sentence, so that people and tools can search, count, and compare logs reliably. OpenTelemetry gives these records a standard shape, called the log data model, with fields for time, severity, body, attributes, resource, and trace context. Existing logging libraries connect to it through bridges, logs can leave applications directly or through files read by a Collector, and the Collector can parse, enrich, filter, and redact on the way. The greatest prize is correlation: logs that carry trace and span identifiers connect seamlessly to the traces that produced them. Use stable messages, standard names, honest severity, careful privacy habits, and sensible volume controls, and your logs will become one of the most powerful tools you have.
Key Takeaways
- Structure turns text into data — named fields let tools search, filter, group, and count logs precisely, instead of guessing at wording.
- A shared data model — OpenTelemetry defines a standard log record with timestamp, severity, body, attributes, resource, scope, and trace context.
- Stable message, rich attributes — keep the message constant for each kind of event and put changing facts into attributes.
- Severity on a common scale — a numeric scale from one to twenty-four in six bands makes levels from different libraries comparable.
- Correlation with traces — trace and span identifiers attached to logs let you jump between a log line and the request that produced it.
- Bridges and the Collector — keep your existing logging library via a bridge, and use the Collector to parse legacy logs, enrich, filter, and redact.
- Mind cost and privacy — control volume with severity and filters, never record secrets, and use the Collector as a safety net for sensitive data.