Centralised logging
Ship container logs to Loki or ELK and query them.
By Invicly Tech, , in Full DevOps with Python. About 12 minutes to read.
In short
Centralised logging collects logs from every container into one searchable place. Structured JSON logs with request IDs let you filter by service, level or a single user request.
Explained simply
A log is a line of text your program writes when something happens: a request arrived, an order was saved, a payment failed. On one server you can read logs with a text tool. With 30 containers that move between machines and disappear when they restart, you need one central place that collects them all.
Centralised logging works like this: every app writes logs to standard output, a small agent on each machine picks them up, adds labels such as app name and namespace, and sends them to a log store. You then search all logs from one web page.
Logs are far easier to search when each line is structured, usually as JSON with named fields like level, message and request_id. Then you can ask for all ERROR lines for one request instead of guessing with text search.
The two popular stacks are Loki with Grafana, and ELK (Elasticsearch, Logstash and Kibana). Loki is cheaper to run because it only indexes a few labels. Elasticsearch indexes the full text, which makes searches faster and more flexible but needs much more storage and memory.
Press Play on a diagram to walk through it one step at a time.
- 1App logs JSON
One JSON object per line to stdout.
- 2Runtime stores logs
Container runtime writes stdout to node log files.
- 3Agent ships logs
Grafana Alloy or Promtail adds labels and sends them.
- 4Loki stores
Indexes labels only; compresses the log lines.
- 5Grafana queries
LogQL filters by labels, then parses JSON fields.
- 1Stream selector
{app="api", namespace="prod"}
- 2Line filter
|= "checkout" drops most lines fast
- 3Parser
| json turns fields into labels
- 4Label filter
| level="ERROR"
- 5Format or aggregate
line_format, or count_over_time
In depth
Structured logging in Python
Python's logging module has three parts that matter: loggers (logging.getLogger(__name__)) that your code calls, handlers that decide where records go, and formatters that turn a record into text. For containers, use one StreamHandler on stdout and a JSON formatter. You can write a small formatter yourself, or use python-json-logger or structlog.
Keep a stable set of fields on every line: timestamp in ISO 8601 UTC, level, logger name, message, service, and request_id. Pass details as fields, not inside the message text: log.info("order created", extra={"order_id": 42}) produces a field you can filter on, while an f-string buries the number in a sentence.
Log at the right level: DEBUG for developer detail (off in production), INFO for normal events, WARNING for something odd that recovered, ERROR for a failed operation. log.exception() inside an except block adds the traceback. Never log passwords, tokens, full card numbers or personal data; once shipped, they are hard to delete.
- Configure logging once at startup, not in every module
- Uvicorn has its own loggers (uvicorn, uvicorn.access); format them too
- One JSON object per line, so the agent never splits a record
How container logs travel to the store
When a container writes to stdout or stderr, the container runtime saves those lines to a file on the node. With Docker's default json-file driver, that is a file named after the container ID ending in -json.log under /var/lib/docker/containers/, and docker logs reads it. In Kubernetes, the kubelet keeps them under /var/log/pods/, with symlinks in /var/log/containers/, and kubectl logs reads them through the kubelet. The kubelet rotates these files (by default at 10 MiB, keeping 5 files), so node files are not long-term storage.
A log agent runs on every node, usually as a DaemonSet in Kubernetes. It tails those files, remembers its position so a restart does not resend lines, adds metadata from the Kubernetes API (namespace, pod, container, app label) and ships batches to the store. For Loki the current agent is Grafana Alloy; Promtail is deprecated. For ELK, Filebeat or Fluent Bit are common. If the store is down, agents buffer and retry.
- 1Grafana or Kibana
Search and dashboards
- 2Loki or Elasticsearch
Central store with retention
- 3Agent DaemonSet
Alloy, Fluent Bit or Filebeat adds labels
- 4Node log files
/var/log/pods, rotated by kubelet
- 5Container stdout
Your app writes one JSON line
Loki vs ELK: what gets indexed
The big design choice is what you index. Loki groups log lines into streams by their label set, for example {app="api", namespace="prod"}, and indexes only those labels. The lines themselves are compressed into chunks, often in object storage like S3. A query first picks streams by label, then scans their lines. This keeps storage cheap, but a broad query over many days can be slow.
Elasticsearch builds an inverted index of every word in every field, like the index at the back of a book. Any full-text search is fast, and Kibana offers rich analysis, but the index can be as large as the data and the cluster needs plenty of RAM and careful tuning.
For Loki, labels must have low cardinality: app, namespace, environment, level at most. A request_id or user_id label creates a new stream per value and hurts performance badly; keep those inside the JSON line and filter with a parser at query time.
- Indexes labels only
- Lines compressed in object storage
- Cheap, simple to run
- Queries narrow by label first
- Indexes every field and word
- Index can be as big as the data
- Fast full-text search
- Needs more RAM and tuning
Querying with LogQL
Every LogQL query starts with a stream selector in braces: {namespace="prod", app="api"}. Then you add a pipeline. Line filters are fast text checks: |= "timeout" keeps lines containing timeout, != excludes, |~ uses a regular expression. Put line filters early, because they are cheap.
Parsers turn the line into fields: | json for JSON logs, | logfmt for key=value logs. After parsing, label filters compare fields: | level="ERROR" or | duration_ms > 500. | line_format can reshape the output for reading.
LogQL can also produce metrics from logs. count_over_time({app="api"} |= "ERROR" [5m]) counts matching lines per stream, and sum by (level) (count_over_time({app="api"} | json [5m])) graphs lines per level. That lets you alert on log patterns, though counters in Prometheus are cheaper for anything you query often. In Grafana, use Explore with the Loki data source, and narrow the time range before running heavy queries.
Following one request with a request ID
When a user reports an error, you want every log line from that one request, across every service it touched. The trick is a request ID: a unique value, usually a UUID, created at the edge and passed along.
In practice: the load balancer or the first service checks for an incoming X-Request-ID header and creates one if it is missing. A middleware stores it in a contextvars.ContextVar, which is safe with async code because each request gets its own context. A logging filter copies it into every record, so you never pass it by hand. Every outgoing HTTP call adds the same header, and the response returns it to the client, so support staff can ask the user for it.
Then one LogQL query finds the story: {namespace="prod"} | json | request_id="8f3c...". Full distributed tracing with OpenTelemetry takes this further, using the W3C traceparent header and a trace_id you can also log, linking logs to traces.
- Client to API: POST /checkout (no ID)1POST /checkout (no ID)
- 2Create request_id=8f3c, log itAPI to API: Create request_id=8f3c, log it
- API to Orders service: Call with X-Request-ID: 8f3c3Call with X-Request-ID: 8f3c
- Orders service to Loki: Log ERROR with request_id 8f3c4Log ERROR with request_id 8f3c
- API to Client: 500 with X-Request-ID: 8f3c5500 with X-Request-ID: 8f3c
- Client to Loki: Support searches request_id=8f3c6Support searches request_id=8f3c
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Log structured JSON from the app~45m
- 2Ship container logs to Loki or ELK~45m
- 3Query and filter logs by label~45m
- 4Correlate logs with request IDs~45m
Key points
- Log to stdout and let the platform collect logs, rather than writing files in the container.
- Structured JSON makes fields like level and request_id searchable.
- Loki labels should be low-cardinality, like app and namespace, not user IDs.
- Pass a request ID through every service to follow one request end to end.
Key terms
Tap a card to flip it. 0/5 known
Examples
import json, logging, sys, uuid
class JsonFormatter(logging.Formatter):
def format(self, record):
return json.dumps({"level": record.levelname, "msg": record.getMessage(),
"request_id": getattr(record, "request_id", None)})
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("api")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.info("order created", extra={"request_id": str(uuid.uuid4())})
# LogQL: {app="api"} | json | level="ERROR"JSON logs to stdout, then filter errors in Grafana.
Add request IDs to every log line in FastAPI
Step 1: a ContextVar holds the current request ID. Step 2: a middleware reads X-Request-ID or creates a UUID, sets the ContextVar, and echoes the ID in the response. Step 3: a logging.Filter copies the value into every record, so any log call in any module gets it. Step 4: the JSON formatter prints it as a field. Now one search by request_id shows the whole request.
import contextvars, json, logging, sys, uuid
from fastapi import FastAPI, Request
request_id = contextvars.ContextVar("request_id", default="-")
class AddRequestId(logging.Filter):
def filter(self, record):
record.request_id = request_id.get(); return True
h = logging.StreamHandler(sys.stdout); h.addFilter(AddRequestId())
h.setFormatter(logging.Formatter('{"level":"%(levelname)s","msg":"%(message)s","request_id":"%(request_id)s"}'))
logging.basicConfig(level=logging.INFO, handlers=[h])
app = FastAPI()
@app.middleware("http")
async def add_id(request: Request, call_next):
request_id.set(request.headers.get("x-request-id") or str(uuid.uuid4()))
response = await call_next(request)
response.headers["X-Request-ID"] = request_id.get(); return responseInvestigate a spike of checkout errors in Grafana
Step 1: in Explore, choose the Loki data source and the last 30 minutes. Step 2: graph errors per minute to see when the spike started. Step 3: list the error lines, parsed from JSON, and read the messages. Step 4: pick one request_id from a failing line. Step 5: search all namespaces for that ID to see what the downstream services logged for the same request. Step 6: once you know the pattern, turn the count query into an alert.
# 1. errors per minute for the api
sum(count_over_time({namespace="prod", app="api"} | json | level="ERROR" [1m]))
# 2. the error lines, readable
{namespace="prod", app="api"} |= "checkout" | json | level="ERROR"
| line_format "{{.request_id}} {{.msg}}"
# 3. everything for one request, in every service
{namespace="prod"} |= "8f3c2a" | json | request_id="8f3c2a"Quick reference
- Log to stdout as one JSON object per line; let the platform collect it
- Loki listens on port 3100; Elasticsearch on 9200; Kibana on 5601
- Loki labels: app, namespace, env, level. Never request_id or user_id
- {app="api"} |= "error" filters text; | json then parses fields
- count_over_time({app="api"} |= "ERROR" [5m]) turns logs into a metric
- kubectl logs -l app=api --since=10m --prefix shows recent lines from all matching Pods
- Promtail is deprecated; ship logs to Loki with Grafana Alloy
- Echo X-Request-ID in responses so users can quote it to support
Common mistakes
- Using request_id as a Loki label, which explodes the index; keep it in the log line.
- Logging passwords, tokens or personal data that then lives in the log store.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Change a script that uses print() so it logs JSON lines to stdout with level and message fields using python-json-logger.
- Exercise 2medium
Write LogQL that shows, per app in the prod namespace, how many ERROR lines were logged in each 5 minute window.
- Exercise 3hard
Run Loki and Grafana locally with Docker Compose and send one log line to Loki's push API from Python, then find it in Explore.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use Loki or ELK?
- If you already use Grafana and Prometheus and mainly filter by service and time, Loki is cheaper and simpler. If you need fast full-text search and rich analytics across huge volumes, ELK (or OpenSearch) fits better.
- How long should I keep logs?
- It depends on cost and rules: 7 to 30 days of searchable logs is common for debugging, with older logs archived to cheap storage if audits or regulations require it.
- What is the difference between logs, metrics and traces?
- Metrics are cheap numbers over time that tell you something is wrong. Logs are detailed events that tell you what happened. Traces follow one request through every service and show where the time went.
- Why do my Python logs appear late in docker logs?
- Python buffers stdout when it is not a terminal. Set PYTHONUNBUFFERED=1 in the image, or use logging handlers, which flush each record.