Course contents

13. Observability Lesson 1 of 6

Logs

Structured logs, correlation ids, log levels and sampling: follow a failing request by its id and see why errors on every instance point downstream.

13 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A log line records one event; structured lines (constant message + fields) are searchable and aggregatable.
  • A request id created at the edge and passed on with every call ties one request’s lines together across machines.
  • Search by id to see one request’s path; group by a field (instance, route, reason) to see the pattern.
  • Errors spread evenly over every instance point at something they share, such as a database.
  • Keep every error, sample the successes, and count with metrics rather than sampled logs.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A log is a stream of timestamped records, each describing one event in a running program: a request served, a retry, a failed query. Unlike metrics, which aggregate, a log line keeps the detail of the individual event, so it can answer "what happened to this request?".

Why it exists

When something goes wrong you need evidence: which requests failed, where, with what error, since when. Metrics tell you the error rate went up; logs tell you what the failures said. They are also the evidence trail for the review afterwards, and often an audit requirement.

How it works

Producing. Applications write lines to standard output (containers) or files. A collector agent on each host (Fluent Bit, Vector, the OpenTelemetry Collector) tails them, adds metadata (host, pod, service) and ships batches to a log store (Elasticsearch/OpenSearch, Loki, a cloud logging service), which indexes and retains them.

Structured lines. Instead of Order 42 failed after 812ms, write a constant message plus fields: {"level":"error","msg":"order failed","order_id":"42","duration_ms":812,"reason":"db_timeout","request_id":"7f3a9c"}. The store can then filter and group by field without regular expressions. Use consistent field names across services (OpenTelemetry semantic conventions are a good source).

Correlation. The edge (load balancer, gateway) assigns a request id, or accepts one from the caller, and every service passes it on in a header and writes it on every line. With distributed tracing in place, the trace id and span id play this role and also link logs to traces.

Levels. DEBUG for internals, INFO for normal events, WARN for handled anomalies, ERROR for failed operations. Production usually runs at INFO; many runtimes let you raise one logger to DEBUG at runtime for a short investigation.

Sampling. Keep every WARN/ERROR, sample successful INFO lines (1 in 10 or 1 in 100), and record the rate. Some pipelines sample by trace id so that a request's lines are all kept or all dropped together.

When to use it

Always, for events you might need to investigate individually: failures with their reasons, security-relevant actions, state changes, slow operations. Logs are the right tool when the question is about specific requests, users or entities.

When not to

  • For counting and alerting: a metric counter is exact and fixed in cost; sampled logs are not.
  • For timing across services: traces show the call tree and durations directly.
  • For secrets and personal data: passwords, tokens, full card numbers and, in many jurisdictions, emails or IPs must not end up in logs, or need redaction in the pipeline.

Trade-offs

Choice You gain You pay
Structured (JSON) lines Queryable fields, consistent parsing Less readable raw; field discipline across teams
Logging every success Complete history Volume and cost grow with traffic
Sampling successes Most of the cost saved Individual successful requests may be missing
Long retention Investigate slow-burning problems Storage cost, privacy exposure
Rich context fields Faster investigations Risk of leaking personal data; higher cardinality in the index

Alternatives

  • Metrics for counts, rates and distributions.
  • Traces for request paths and latency breakdowns; span events can replace some log lines.
  • Audit logs / event stores for records that must be complete and tamper-evident; do not rely on sampled application logs for those.

Failure modes

  • Unsearchable logs: free-text formats that differ per team, so every query is a regex.
  • Missing correlation: no request id, so a request's lines on different hosts cannot be joined.
  • Log storms: an error inside a hot loop writes millions of identical lines, saturating disks, the pipeline or the budget. Rate-limit repeated messages.
  • Blocking on logging: synchronous writes to a slow sink stall request threads. Log asynchronously with bounded buffers.
  • Sensitive data: credentials or personal data in fields, copied into every backup of the log store.
  • Lost lines: the pipeline drops data under load and nobody monitors the collector's own drop counters.

In production

Standardise a logging library and field names, include service, version, instance and request/trace id on every line, log at INFO by default, redact in the collector as a second line of defence, sample successes, and set retention by what you actually search (often days for debug detail, longer for errors and audit trails). Monitor the pipeline itself.

Common misconceptions

  • "More logs means better observability." Volume without structure or correlation slows investigations and raises cost.
  • "Errors on one dashboard mean one broken host." Group by instance first: an even spread usually points at a shared dependency.
  • "Sampled logs are fine for error rates." Use metrics for rates; sampled logs give estimates at best.
  • "DEBUG in production is harmless." It can multiply volume and expose internals or personal data.

Interview angle

Expect questions like "how would you debug a failed request across five services?" Answer with a correlation (trace) id propagated in headers and written on every structured log line, a central store, and the pattern: metrics show that errors rose, logs grouped by field show where, a single id shows the path. Mention sampling and cost, PII redaction, and that logging must never block requests.

Model assumptions

The requests, failures and their ids are simulated; log lines, the collector, the log store and sampling are scripted illustrations (the purple packets and annotations), not part of the engine. Three app servers have 8 workers each and 15 ms of own work; every request reads the orders database (6 connections, 20 ms per query, 300 ms maximum wait for a connection). The degraded database is 6× slower, so it finishes about 50 queries per second while 60 arrive. Arrivals are Poisson, service times lognormal, network hops a fixed 2–20 ms. Numbers show behaviour and orders of magnitude, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. A log line is a record of one event

    Users send about 60 requests a second. Each passes the load balancer, one of three app servers and the orders database, and every request succeeds.

    Each app server writes a log line for every request it handles: a timestamped record of one thing that happened. Lines go to standard output, a collector (an agent on the host, such as Fluent Bit, Vector or the OpenTelemetry Collector) picks them up and ships them in batches to a log store where you can search them. The purple packets are those lines (scripted; the engine only simulates the requests).

    Scene: Users send about 60 requests per second through a load balancer to three app servers that read the orders database. Every request succeeds. Each app sends log lines to a log collector, which forwards them in batches to the log store.

    Key idea: Logs are discrete event records. They tell you what happened to specific requests, which metrics cannot.

  2. 2. Structured logs: fields, not sentences

    GET /orders/42 200 41ms is easy to read and hard to query. Which field is the latency? Is 42 a user or an order? Every team formats it differently, and every query becomes a regular expression.

    A structured log line is a set of named fields, usually JSON: ts, level, service, instance, route, status, duration_ms, request_id. The log store indexes the fields, so "all 5xx on /orders from app2 slower than 200 ms" is a filter, not a parsing exercise. Write messages as constant strings and put the variable parts into fields.

    Scene: The same system. Log lines are now JSON objects with named fields such as level, route, status and duration, which the log store indexes.

    Key idea: Log fields, not prose: a constant message plus key-value context is what makes logs searchable.

  3. 3. One id for the whole journey

    Traffic is turned down so you can follow one request. The load balancer gives it a request id (or accepts the caller’s) and passes it on in a header. Every component that handles the request puts the id into each log line it writes: the balancer when it routes, App 2 when it answers.

    Watch the order: the request goes in, each hop logs, the answer comes back. In the log store, searching for that one id returns the request’s whole path across machines, in time order. Without it you would be matching timestamps across servers by hand.

    Scene: One request travels from the users through the load balancer to App 2 and the database and back. The load balancer and App 2 each send a log line carrying the same request id to the collector, which forwards them to the log store.

    Key idea: A correlation id, created at the edge and passed on with every call, stitches one request’s log lines together across services.

  4. 4. Errors start

    Traffic is back at 60 a second. One second in, the orders database becomes six times slower. It can now finish about 50 queries a second while 60 arrive, so queries queue for a connection, and a request that waits more than 300 ms gives up with a pool timeout.

    The error tile turns red. Each app server logs the failures at ERROR level with the reason in a field, so the log store can count them by reason: every one of them is a pool timeout.

    Scene: The orders database slows down six times. Queries wait for a connection and some requests fail with a pool timeout; the error rate rises. The app servers log each failure at error level with the reason.

    Key idea: An error log line with a reason field turns "something is failing" into a countable, filterable fact.

  5. 5. Follow a failing request by its id

    Take any red packet’s request id and search for it. Every failing request tells the same story: load balancer → one app server → orders database → pool timeout, then the error travels back.

    Now group the errors by instance: they come from all three app servers, in similar numbers. A fault on one machine would show up on one instance; errors spread evenly over every caller point at something they share. Here that is the database, which is exactly where each request’s trail ends.

    Scene: The database is still slow. Every failing request’s trail goes through the load balancer and one app server and ends at the database with a pool timeout. Errors come from all three app servers in similar numbers.

    Key idea: Search by id to see one request’s path; group by a field (instance, route, reason) to see the pattern.

  6. 6. Log levels decide what is written

    Every line has a level: DEBUG (internals, for developers), INFO (normal events such as a request served), WARN (something odd but handled, such as a retry) and ERROR (an operation failed). Production usually runs at INFO; switching one service to DEBUG for a few minutes is a common debugging move.

    Volume adds up fast. At 60 requests a second, three INFO lines per request are 180 lines a second, about 15.6 million a day. At a few hundred bytes each that is several gigabytes a day, from one small service, before anything goes wrong.

    Scene: The database is still slow and some requests fail. The collector receives about 180 log lines per second at INFO level.

    Key idea: Levels control volume; INFO in production, ERROR for failures you will act on, DEBUG only when you need it.

  7. 7. Sampling: keep every error, not every success

    Most log lines say "request served, all fine". Storing every one of them is the biggest line on many observability bills. A common policy: keep every ERROR and WARN, sample a share of successful INFO lines (say 1 in 10, or 1 in 100), and record the sample rate so counts can be scaled back up.

    Watch the collector: ten lines arrive, one of them an error (red). Two leave: the error, always, and one success in ten. For counting and alerting, use metrics, which see every request; logs are for the detail.

    Scene: Ten log lines reach the collector, one of them an error. The collector forwards the error and one of the nine successes to the log store and drops the rest.

    Key idea: Sample the boring lines, never the errors; count with metrics, not with sampled logs.

  8. 8. The database recovers

    One second in, the slow query behind the incident is stopped and the database recovers. The connection queue drains, pool timeouts stop and the error tile returns to zero.

    The logs now hold the evidence for the write-up: when the first pool timeout happened, how many requests failed, on which routes. Logs are only useful afterwards if they were written, kept and searchable during the incident.

    Scene: The database recovers. Pool timeouts stop and the error rate returns to zero.

    Key idea: Logs are the evidence trail: when it started, what failed, for whom.

  9. 9. What good logging looks like

    Structured lines with constant messages and fields; a request id (or trace id) on every line; levels used consistently; errors always kept, successes sampled; no secrets or personal data in fields; retention set by what you will actually search.

    Logs answer "what happened to this request?". Metrics answer "how much, how often?" far more cheaply, and traces show where the time went. Each lesson in this module covers one of them.

    Scene: The healthy system with its log pipeline: app servers send structured log lines to the collector, which forwards them to the log store.

    Key idea: Logs explain individual events; pair them with metrics for counting and traces for timing.