Logs and traces
About this lesson
Monitoring tells you that checkout got slow. Logs and traces tell you where and why. Follow one checkout request through four services: each program writes log lines that are shipped to one searchable store, a single trace id rides along in the traceparent header, and every service records a span. The span waterfall shows the database query took 950 of 1,250 ms, and searching the logs by that trace id finds the line that explains it. Finally, see how levels, retention and sampling keep the bill under control.
One request, four services
A shopper clicks Pay. The request crosses four services: web, orders, payments and the database. Monitoring shows checkout got slow, but not why. Logs and traces answer where the time went and what went wrong.
web → orders → payments → db, and back monitoring: checkout is slow (a number) logs: what happened inside each program traces: where the time went, end to end
Read the lesson step by step
One request, four services
A shopper clicks Pay. The request crosses four services: web, orders, payments and the database. Monitoring shows checkout got slow, but not why. Logs and traces answer where the time went and what went wrong.
web → orders → payments → db, and back monitoring: checkout is slow (a number) logs: what happened inside each program traces: where the time went, end to endA log line
A log line is one timestamped record of one event, written by the code as it runs. Payments calls log.info("charge start"). Python's logging module adds the level and the logger name, and prints the line.
log.info("charge start", extra=ctx) prints (stdout): INFO pay trace=4bf92f3577b34da6a3ce929d0e0e4736 charge start add %(asctime)s to the format for the timeLevels decide what is kept
Every line has a level. Python's are DEBUG 10, INFO 20, WARNING 30, ERROR 40 and CRITICAL 50. This logger is set to INFO, so log.debug is dropped at the source and log.warning is kept.
DEBUG 10 · INFO 20 · WARNING 30 · ERROR 40 · CRITICAL 50 level=logging.INFO: keep 20 and up log.debug("card ok", extra=ctx) dropped (10 < 20) log.warning("db slow", extra=ctx) kept (30 ≥ 20)Ship every line to one store
Each program writes its lines to standard output. In Kubernetes the node saves them per container, and kubectl logs reads them back. A log agent on every node ships all the lines to one central store you can search.
program → stdout → node saves per container kubectl logs <pod> one pod at a time agent on each node → central log store payments INFO charge start payments WARNING db slow web INFO GET /checkout orders INFO order created web INFO 200 in 1250 ms orders INFO charge sent db LOG duration: 950 msStructured logs: named fields
Lines with named fields, like a level and trace=4bf9…, are structured logs. A machine can filter them without guessing at free text. Here extra=ctx stamps the same trace id on every payments line.
ctx = {"trace_id": tid} every line now carries trace=<id> query: level = WARNING payments WARNING db slow (1 match) many teams print JSON: one field per keyOne trace id per request
Logs belong to one program; a trace follows one request through all of them. Web picks a random 32-hex-digit trace id and passes it on in a traceparent header (the W3C Trace Context standard). Every service forwards it.
traceparent: version-traceid-parentid-flags 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 trace id 16 bytes, 32 hex digits, same everywhere parent id 8 bytes, the caller's span flags 01 = sampled (recorded)Spans build the waterfall
Each service records a span: one timed piece of work with a name, a start, a duration and its parent span. Payments' span is a child of orders' span. The four spans form a tree, drawn here as a waterfall.
web GET /checkout start 0 ms 1250 ms orders POST /orders start 20 ms 1200 ms payments charge start 60 ms 1120 ms db SELECT start 140 ms 950 ms parent → child: web → orders → payments → dbFind the slow span
Read the waterfall. The request took 1,250 ms and the database query alone took 950 ms. Self time is a span's duration minus its children's: the database has 950 ms, payments only 170 ms. Fix the query first.
self time = duration − children web 1250 − 1200 = 50 ms orders 1200 − 1120 = 80 ms payments 1120 − 950 = 170 ms db 950 − 0 = 950 ms db: 950 of 1250 ms = 76 %Join logs and traces
Now join the two. Search the log store for this trace id and you get exactly this request's lines, including payments' WARNING "db slow". The trace says where the time went; the log line says what happened there.
query: trace_id = 4bf92f3577b34da6a3ce929d0e0e4736 7 lines, from all four services payments WARNING db slow db LOG duration: 950 ms trace → where; log → whatKeep the cost down
Storing everything costs money. Teams log at INFO, not DEBUG, in production, delete old logs after a set time, and sample traces: keep, say, 1 trace in 10, decided at the first service and carried in the sampled flag.
level: INFO in production, not DEBUG retention: delete after N days (30 here) sampling: keep 1 trace in 10 (head sampling) 01 = kept, 00 = not recorded
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A logger is set to level INFO. Which of these calls produce a line?
Python's levels are DEBUG 10, INFO 20, WARNING 30, ERROR 40 and CRITICAL 50. A logger set to INFO keeps records at 20 and above, so DEBUG (10) is dropped.
02Where should a program in a container write its logs so Kubernetes can collect them?
Kubernetes saves each container's stdout and stderr on its node; kubectl logs reads them, and a node-level agent can ship them to a central store.
03What does the traceparent header carry from one service to the next?
W3C Trace Context: version-traceid-parentid-flags. The 32-hex-digit trace id stays the same across every service; the parent id names the calling span.
04Spans: web 1,250 ms, orders 1,200 ms, payments 1,120 ms, database 950 ms, each the child of the one before. Which has the largest self time?
Self time is a span's duration minus its children's. Web 50 ms, orders 80 ms, payments 170 ms, the database 950 ms: the query is where the time goes.
05Which is NOT a usual way to control the cost of logs and traces?
A new trace id at every hop would break the trace apart; it saves nothing. Levels, retention and sampling are the usual cost levers.
Glossary
- Log line
- One timestamped record of one event, written by a program as it runs, for example INFO pay trace=4bf9… charge start.
- Log level
- How serious a log line is. Python's levels are DEBUG 10, INFO 20, WARNING 30, ERROR 40 and CRITICAL 50; a logger drops lines below its level.
- Structured log
- A log line made of named fields (such as level, trace_id, message), often printed as JSON, so machines can filter and search it.
- Log store
- A central system that collects the logs of every program and lets you search them, for example by trace id.
- Trace
- The whole journey of one request through every service it touches, made of spans that share one trace id.
- Span
- One timed piece of work inside a trace, with a name, a start time, a duration and the id of its parent span.
- traceparent
- The W3C Trace Context HTTP header that carries the trace id, the caller's span id and flags from one service to the next.
- Sampling
- Recording only some traces, for example 1 in 10, to keep storage costs down. Head sampling decides at the first service.
Notes and sources
- The checkout, its four services and its timings are an illustration, not a measurement. The arithmetic holds: the spans nest, and their self times add up to the whole 1,250 ms.
- The code card is the core of a real Python 3 program; the full program adds logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(levelname)s %(name)s trace=%(trace_id)s %(message)s") and the trace id. It prints two lines: the DEBUG line is filtered out.
- In the W3C Trace Context header the trace id is 16 bytes (32 hex digits) and the parent id 8 bytes (16 hex digits); the last field holds flags, where 01 means sampled. The trace id used here is the example from the specification.
- Kubernetes keeps each container's stdout and stderr on its node and rotates the files (by default at 10 MiB, keeping 5). Logs on a node are lost with the node, which is why a node-level agent ships them to a central store.
- Head sampling decides at the first service whether to record a trace; tail sampling decides after the trace is complete, so it can keep every slow or failed one. Retention periods such as 30 days are a team choice, not a standard.
- Tools differ, but the ideas are the same: OpenTelemetry is the open standard for producing traces and logs, and many backends store and search them.
- Python docs: logging (levels, basicConfig, extra)
- Python docs: Logging HOWTO
- Kubernetes: Logging Architecture
- The Twelve-Factor App: XI. Logs
- W3C Recommendation: Trace Context
- OpenTelemetry: Traces
- OpenTelemetry: Logs
- OpenTelemetry: Sampling
- PostgreSQL docs: Error Reporting and Logging (log_min_duration_statement)
- Google SRE book, ch. 12: Effective Troubleshooting
- Google SRE book, ch. 6: Monitoring Distributed Systems
- Sigelman et al., Dapper, a Large-Scale Distributed Systems Tracing Infrastructure (Google, 2010)
Quiz Unlocks after the last step.