Centralised Logging with Loki

Ship logs from every host and pod to Grafana Loki, a cost-efficient log store that indexes labels rather than full text.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Observability Fundamentals

When services run on many machines and pods come and go, ssh plus grep stops working. You need logs shipped off each host to a central store. Grafana Loki is our default pick for new setups because it is cheap to run and fits naturally next to Prometheus and Grafana.

How Loki is different

Loki indexes only a small set of labels (namespace, app, pod, level) and stores log lines compressed in object storage. Queries first select streams by label, then filter the text. That makes storage cheap, but it means you must keep labels low-cardinality, just like Prometheus.

The pipeline

  1. Apps write structured logs to stdout/stderr (in containers) or files.
  2. An agent collects them: Grafana Alloy, Promtail (older), Fluent Bit or the OpenTelemetry Collector. In Kubernetes it runs as a DaemonSet and adds pod metadata as labels.
  3. Loki stores them in object storage (S3, GCS, Azure Blob) with a retention policy.
  4. You explore in Grafana with LogQL.

LogQL basics

  • {namespace="shop", app="api"} |= "error": select streams, filter lines.
  • | json | status >= 500: parse JSON fields and filter on them.
  • sum by (app) (rate({namespace="shop"} |= "timeout" [5m])): turn logs into metrics for dashboards and alerts.

Good logging practice

Log in JSON with consistent keys (level, msg, trace_id, service), never log secrets or full personal data, avoid logging every successful request at high volume, and set retention per environment.

Good enough to move on: you can deploy Loki with an agent on a cluster, find all 5xx errors for one service in the last hour with LogQL, jump from a log line to its trace, and set a retention policy.

Key concepts

  • Label-based indexing
  • Log agents: Alloy, Fluent Bit
  • Kubernetes log collection
  • LogQL filters and parsers
  • Metrics from logs
  • Object storage and retention
  • Logging hygiene and PII

Other options for this step

Mini project

Add Loki and a log agent to your local monitoring stack, make your app emit JSON logs with trace IDs, and build a Grafana panel that counts errors per service from logs.

Check yourself

Why would adding request_id as a Loki label be a mistake, and how do you search for a request ID instead?

Free resources