Logs

What a log is, precisely

A log record is an immutable, timestamped description of one discrete event that happened in a process. A log (or log stream) is the ordered sequence of such records from a source. Two properties define the signal: records are append-only (you never update a past line) and event-granular (one line per thing that happened, not per time interval). That second property is what separates a log from a metric.

Unstructured vs structured

An unstructured log is free text that a human reads; machines must guess its fields with regexes. A structured log is emitted as key-value pairs in a machine-parseable format, most often JSON or logfmt (key=value pairs on one line).

✗ Unstructured: parse with a regex, break when someone edits the message

2026-10-24 10:15:03,123 INFO  OrderService - Order 9913 created for user 42 in 87ms

✓ Structured JSON: fields are addressable, message is constant

{"ts":"2026-10-24T10:15:03.123Z","level":"info",
 "msg":"order created","service":"order",
 "order_id":9913,"user_id":42,"duration_ms":87,
 "trace_id":"4bf92f3577b34da6a3ce929d0e0e4736",
 "span_id":"00f067aa0ba902b7"}
ts=2026-10-24T10:15:03.123Z level=info msg="order created" service=order order_id=9913 user_id=42 duration_ms=87 trace_id=4bf92f35…

The structured line wins on three counts. (1) Parse cost: a JSON parse is one pass with known keys, while a regex with alternations and backtracking typically costs several times more CPU per line in the agent, and it runs on every node. (2) Stability: msg is a constant string, so you can group by it (“how many order created per minute”) and variable data lives in fields. (3) Queryability: duration_ms > 500 is a numeric comparison, not a string hunt. The price is bytes: field names repeat on every line (the JSON above is ~230 bytes against ~80), which compression mostly recovers (typically 5-10x on repetitive logs).

Log levels

A log level (severity) classifies how important a record is, so you can filter at the source. The classic ladder is below; the right-hand column is the OpenTelemetry SeverityNumber, a 1-24 integer that normalises every language's level names (four sub-levels per band, e.g. 9 = INFO, 10 = INFO2).

LevelOTel SeverityNumberMeaningOn in production?
TRACE1-4Finest-grained flow, per-iteration detailNever
DEBUG5-8Diagnostic detail for developersOff by default; enable per-service on demand
INFO9-12Normal business event: state change worth recordingYes
WARN13-16Unexpected but handled: retry, fallback, degradedYes
ERROR17-20An operation failed; someone should eventually lookYes
FATAL21-24Process cannot continue and is about to exitYes

The line that matters is ERROR: log ERROR only when the operation failed and was not handled. A caught-and-retried timeout is WARN. Teams that log every 404 as ERROR end up with an error-log volume that no one trusts, and an alert on it that pages for nothing. Note that SeverityText (the original string such as “Warning” or “CRITICAL”) is kept alongside the number because not every framework maps cleanly.

Anatomy of a good log line

TimestampRFC 3339 in UTC with sub-second precision (2026-10-24T10:15:03.123Z). Never local time without an offset; never 10/24/26.
LevelOne of the fixed set above, lowercase or uppercase, but consistent across services.
MessageConstant human-readable event name. Variables go in fields, not interpolated into the string.
Service identityservice.name, version, instance. Usually added by the agent as resource metadata, not by app code.
Correlationtrace_id, span_id, and a request_id for non-traced paths.
Business keysThe IDs you would grep for: order_id, tenant_id. Fine in logs, fatal as metric labels (see Metrics).

A correlation ID (request ID) is one identifier stamped on every record produced while serving one request, across all services, so you can reassemble that request's story with a single filter. In practice use the W3C Trace Context trace_id (32 hex chars) rather than inventing your own, so logs join to traces for free: {service="order"} | json | trace_id="4bf92f35…". Most logging libraries support this by reading the active span from context in a log-formatter hook; the OTel SDK does it automatically when you log through its bridge.

Kinds of logs

KindRecordsVolumeRetention / handling
Access logOne line per request at the edge: method, path, status, bytes, latency, client IP (nginx, Envoy, ALB)Very high, perfectly proportional to trafficShort hot retention; often sampled or reduced to metrics. Source for RED metrics when apps are not instrumented.
Application logWhat your code decides to say: decisions, errors, warningsProportional to verbosity, easy to inflate by accidentDays to weeks; the main target of sampling and level filtering.
Audit logWho did what to which resource and when (login, permission change, data export)LowMust not be sampled or dropped; append-only, tamper-evident, retained for compliance (often 1-7 years); separate pipeline and store.
Event logDomain/business events (order placed, payment captured), sometimes the system of record (event sourcing)MediumTreated as data, not diagnostics; a Kafka topic or warehouse rather than a log index.

Where logs go

The rule: your app just prints its logs to the screen (stdout, or stderr for errors). That's it. The app does not open log files, does not decide when to start a new file, and does not send logs anywhere. Something else does all of that. This is called the twelve-factor app rule.

Why: in Kubernetes your app runs in a container that can be killed and moved at any time. Any file it writes inside itself dies with it. So the app prints, and the platform keeps the log safe.

What happens to one log line, step by step:

  1. The app prints a line. Example: {"level":"info","msg":"order created"}
  2. The container runtime saves it to a file on the machine. The runtime is the program that runs containers (containerd or CRI-O). It catches everything the app prints and writes it to a file on the node: /var/log/pods/<namespace>_<pod>_<id>/<container>/0.log. There is also a shortcut to the same file in /var/log/containers/.
    It adds three things to the front of each line: the time, which stream it came from (stdout or stderr), and a letter. F means "full line". P means "part of a line": a very long line (over about 16 KB) gets cut into pieces, and someone has to glue them back.
  3. An agent on the same machine reads the file. This is a small program running on every node (a DaemonSet), like Fluent Bit, Grafana Alloy, Vector, or the OTel Collector with its filelog receiver. It reads new lines as they are added (tailing), like tail -f.
    • It writes down how far it has read in each file (an offset), and saves that to disk. If the agent restarts, it carries on from where it stopped. Without this it either reads everything again (duplicates) or skips what it missed (gaps).
    • It asks Kubernetes "which pod is this file from?" and adds labels like pod name and namespace, so you can search by them later.
  4. The agent sends the lines to a store (Loki, Elasticsearch, ClickHouse, S3), where you can search them.

Machines without containers (a plain Linux server) have two older places logs go:

  • journald: the system's own log book on most Linux machines. You read it with journalctl, and agents have an input that reads it too.
  • syslog: an old, simple way to send log lines over the network. Each line has a source type (facility) and a level (severity). Careful: over UDP it quietly loses lines when it gets busy, and nobody is told.

In one line: the app prints, the runtime saves to a file, the agent reads the file and sends it on. The diagram below follows one line through those steps and shows where it can get lost.

Seven stages: application writes to stdout, the container runtime adds a timestamp and stream tag, the line lands in a node file that kubelet rotates, a node agent tails it with an offset file, parses and enriches it, batches and ships it, and a backend indexes and stores it. Red failure boxes sit under the stages where data is lost or damaged.
From logger call to queryable record — and where lines are lost. Read it as: a log line is handed over six times before anyone can search it, and each hop has its own loss mode. The node file line at the bottom is what the agent actually sees: your JSON is wrapped in a CRI prefix.

Log rotation

The problem: an app that keeps printing logs would fill up the machine's disk forever. So the log file can't just keep growing.

The fix (rotation): when the file gets too big, close it, start a fresh empty file, and keep only the last few old ones. The oldest one gets deleted. In Kubernetes, kubelet (the program that runs pods on each node) does this for you with two settings:

  • containerLogMaxSize: how big one file can get before a new one starts. Default 10 MiB.
  • containerLogMaxFiles: how many files to keep per container. Default 5.

So each container keeps about 50 MiB of logs on the node. Anything older is gone from the node.

Where it goes wrong: rotation doesn't wait for the agent. If a busy pod writes logs faster than the agent reads them, the oldest file gets deleted while it still has lines the agent never read. Those lines are lost, and nothing tells you. You just see a gap later.

  • If a file is only renamed (the first step of rotation), the agent is fine. It still has the file open and keeps reading.
  • If a file is deleted before the agent finishes it, the rest is gone.

Rule of thumb: the agent must send logs out faster than the pods on that node write them. If not, rotation will eventually delete lines the agent never read. Example: a pod writing 5 MiB/s fills the 50 MiB window in 10 seconds. If the agent pauses for longer than that, lines are lost.

Sampling and rate-limiting

Sometimes there are just too many logs: too expensive to store, too noisy to read. Two ways to cut them down:

  • Sampling: keep only some of them, for example 1 in 10.
  • Rate limiting: keep at most N per second, for example "max 10 per second from this service". The rest are dropped.

You can do this in three places: in the app's logger, in the agent or Collector, or at the backend (which refuses data over a limit). Rules so you don't throw away the logs you need:

  • Cut by level. Keep every WARN, ERROR and FATAL. Only sample INFO, and only from busy code paths (keep 1-10%). Never sample audit logs.
  • Keep whole requests, not random lines. If you keep a request, keep all of its lines. Do this by deciding on the trace_id (same trace ID → same decision), not by a coin flip per line. Otherwise you end up with half a story. Same idea as the Distributed Tracing guide.
  • Squash repeats. If the same message from the same service shows up over and over, keep a few per second, then write one line like "this repeated 49,990 more times". A retry loop or a bad deploy printing 50,000 identical lines a second is the most common cause of a surprise bill.
  • Count instead of keep. If you only ever count some lines (like "how many requests"), turn them into a metric (a number) and throw the lines away. A number is far cheaper to store.

PII and secrets in logs

Why logs are risky: one log line gets copied to many places: the node, the agent, Kafka, the log store, maybe a vendor. Far more people can read logs than can read your database. And when a user asks "delete my data", logs are usually forgotten.

So two kinds of data should never be logged:

  • PII (personal info): email, phone number, name, home address, and in some countries even IP address.
  • Secrets: passwords, API keys, tokens, session cookies, the Authorization header.

How to stop it, in layers (each one catches what the last one missed):

  1. Don't log whole requests or responses or all headers by default. That's where most leaks come from.
  2. List what is allowed, not what is banned. "Only log these 8 fields" is safe. "Log everything except password" misses the field someone adds next month.
  3. Clean it in the agent or Collector as a safety net: find card numbers and tokens with patterns and replace them with ***.
  4. Make secrets hide themselves in code. Wrap them in a Secret type that prints as ***, so even log(secret) is harmless.
  5. Test it. Have CI check sample log output for things that look like secrets or personal data.

Important: cleaning in the pipeline is a safety net, not the plan. Once a token has been sent to a vendor, you can't take it back.

Cost economics

You pay for logs in three ways:

  • Ingest: for every GB you send in.
  • Indexing: for making them searchable.
  • Retention: for how much you keep, times how long you keep it.

Vendors usually charge somewhere around $0.10 to $1.50 per GB just to take logs in. Making them searchable is often priced separately and costs more. (Prices change, so check the current price list before quoting a number.)

Quick math: 500 machines × 1 GB of logs a day each = 500 GB a day = 15 TB a month. At $0.50 per GB, that's $7,500 a month just to send them in, before you search or store anything.

So logs are kept in tiers: new logs on fast, expensive storage, older logs on slow, cheap storage.

TierHow oldKept onHow fast to search
Hot0-7 daysFast disks (SSD), fully searchableInstant. This is what you use during an incident.
Warm7-30 daysCheaper disks or object storage, less searchableA few seconds
Cold / archive30 days to yearsObject storage like S3, compressedSlow, or you first copy it back into a searchable store. Used for audits and rare investigations.

The biggest cost choice is how much you make searchable:

  • Elasticsearch builds an index of every word. Any search is fast, but the index is big, often several times bigger than the logs themselves.
  • Loki only indexes a few labels (like service and pod) and stores the log text compressed. Much cheaper, but searching inside the text is slower because it has to scan.

Details in the Log pipelines and storage part.

The OpenTelemetry log data model

Logs come in many shapes: JSON, plain text, syslog, Kubernetes file lines, Windows events. OpenTelemetry defines one common shape, called a LogRecord, so every log can be turned into it. Then every tool can read every log the same way. This shape is Stable, meaning it won't change under you.

FieldTypeWhat it holds
Timestamptime in nanosecondsWhen it happened, according to the app that wrote it
ObservedTimestamptime in nanosecondsWhen the collector first got it. Useful when the source has no clock, or a wrong one.
SeverityText / SeverityNumbertext / number 1-24The level as the app wrote it ("WARN") / the same level as a number, so different tools sort it the same way
Bodyany valueThe log message itself: plain text, or a set of fields for structured logs
Attributeskey-value pairsDetails about this one event: order_id, http.response.status_code
Resourcekey-value pairsWho sent it: service.name, k8s.pod.name, cloud.region
InstrumentationScopename + versionWhich library in the app produced it
TraceId / SpanId / TraceFlagsIDsWhich request (trace) was running when the log was written. This is how you jump from a log to its trace.
EventNametextSet when the record is a named event, not a normal log line (see Beyond the three pillars)

Two things worth remembering:

  • Resource vs Attributes: Resource is the same for every log from one process (same service, same pod), so it's sent once per batch, not on every line. Attributes change per line. That split is what keeps OTLP small.
  • Why two timestamps: when an agent reads a log from a file, it may get there seconds or minutes late. The real time is what the app wrote (Timestamp). When the agent saw it is a different time (ObservedTimestamp). Keeping both means a slow agent doesn't make logs look like they happened later.

How these fields are sent over the wire is in the OpenTelemetry part.

Traps

The Invariants

  • Guarantees: A kept record preserves the full detail of one event, in order per source, and can carry the trace_id that joins it to a trace. A structured line costs a constant amount to parse regardless of message wording.
  • Does not guarantee: Delivery: stdout buffers, rotation races, agent drop-on-full and UDP syslog all lose lines without an error in the app. Nor ordering across sources (clocks skew), nor that a line was emitted at all, since absence of a log is not proof the code did not run. Nothing here makes volume cheap: cost scales with traffic × verbosity.