Centralised logs with Loki
Ship every server and container log to one place with Grafana Alloy and Loki, search them with LogQL, and know when the Elastic Stack, Graylog or Splunk is the better fit.
By the end of this lesson you'll be able to
0 of 5 completeWhen a service runs on six servers, finding one error means SSH-ing into each and running grep,
and the logs of a replaced container are simply gone. In this lesson you'll ship every log to one
place with Grafana Alloy and Loki, search them with LogQL in Grafana, and hunt down real
errors from a multi-service demo app.
How Loki stores logs
The key idea is the stream: all log lines that share exactly the same set of labels. For
example, {container="hotrod", host="lab-1"} is one stream.
When a batch of lines arrives, Loki does three things:
- It finds the stream from the labels, creating a new one if this label set is new.
- It appends the lines to that stream's current chunk and compresses it.
- It records in a small index which chunks belong to which labels and time range. The chunks themselves go to object storage (S3, GCS, Azure) in production, or local disk in a lab.
A query works backwards: the labels in {...} pick streams from the index, then Loki decompresses
only those chunks for the time range and filters the lines, a bit like a very fast distributed
grep.
That design is why Loki is cheap. The index is tiny compared with indexing every word. The cost is that a search across all streams for a rare word reads a lot of data. So you always start a query with labels that narrow it down.
Labels: few, and low-cardinality
Cardinality is how many distinct values a label has. level has five, host has dozens: fine.
user_id, request_id or trace_id have millions. Each new value makes a new stream, so the index
balloons and every stream holds a handful of lines. Loki's own guidance is to keep labels few and
bounded.
Put high-cardinality values in the line, and filter for them at query time:
{container="checkout"} |= "user_id=8812" # good: filter inside one stream {container="checkout", user_id="8812"} # bad: a stream per user
Run Loki and Grafana Alloy
The lab ran Loki 3.7.9 and Alloy 1.21.3 on the Docker network from lesson 2, next to HotROD, an official Jaeger demo app: a fake ride-booking service made of frontend, customer, driver and route services that logs every step. You'll use the same app for tracing in the next lesson.
$ docker run -d --name loki --network mon -p 3100:3100 grafana/loki $ curl -s localhost:3100/ready ready $ docker run -d --name hotrod --network mon -p 8080:8080 \ -e OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318 jaegertracing/example-hotrod all
docker run -d --name loki --network mon -p 3100:3100 grafana/lokidockerbuild and run containersrunstart a new container-drun in the background--name lokiname the container--network monwhich network to join-p 3100:3100publish a port, host:containergrafana/lokithe image to start
curl -s localhost:3100/readycurlmake an HTTP request-ssilent: no progress bar
docker run -d --name hotrod --network mon -p 8080:8080 \--name hotrodname the container-p 8080:8080publish a port, host:container\the image to start
Alloy's config is a set of components, each with a type and a name, wired together by passing one component's output to the next:
// config.alloy // Find every container on this Docker host. discovery.docker "containers" { host = "unix:///var/run/docker.sock" } // Turn Docker's metadata into a small set of Loki labels. discovery.relabel "containers" { targets = [] rule { source_labels = ["__meta_docker_container_name"] regex = "/(.*)" target_label = "container" } } // Read each container's stdout/stderr and send it on. loki.source.docker "containers" { host = "unix:///var/run/docker.sock" targets = discovery.docker.containers.targets labels = {"host" = "lab-1"} relabel_rules = discovery.relabel.containers.rules forward_to = [loki.write.local.receiver] } loki.write "local" { endpoint { url = "http://loki:3100/loki/api/v1/push" } }
Read it top to bottom:
discovery.dockerasks the Docker socket for every container.discovery.relabelholds one rule: take the container name (Docker reports it as/hotrod), strip the slash, and store it as the labelcontainer.loki.source.dockerreads each container's output, applies those rules, addshost="lab-1", and forwards the lines.loki.writepushes batches to Loki's HTTP API.
$ docker run -d --name alloy --network mon -p 12345:12345 \ -v $PWD/config.alloy:/etc/alloy/config.alloy:ro \ -v /var/run/docker.sock:/var/run/docker.sock \ grafana/alloy run --server.http.listen-addr=0.0.0.0:12345 \ --storage.path=/var/lib/alloy/data /etc/alloy/config.alloy
docker run -d --name alloy --network mon -p 12345:12345 \dockerbuild and run containersrunstart a new container-drun in the background--name alloyname the container--network monwhich network to join-p 12345:12345publish a port, host:container\the image to start
Alloy's web UI on port 12345 draws the pipeline it built from that file, which is the quickest way to see a wiring mistake:
Within a few seconds Loki knows about every container:
$ curl -s localhost:3100/loki/api/v1/labels {"status":"success","data":["container","host","service_name"]} $ curl -s localhost:3100/loki/api/v1/label/container/values {"status":"success","data":["alertmanager","alloy","grafana","hotrod","jaeger","loki","node-exporter","prometheus"]}
curl -s localhost:3100/loki/api/v1/labelscurlmake an HTTP request-ssilent: no progress bar
Loki added service_name by itself: since Loki 3.0 it fills that label in from other labels if
the agent doesn't send one. On servers without Docker, the same idea uses local.file_match and
loki.source.file for log files, or loki.source.journal for systemd's journal.
Older guides use Promtail as the agent. Grafana has replaced it with Alloy, which collects logs,
metrics and traces in one agent. alloy convert --source-format=promtail translates an old
Promtail config.
LogQL: finding the needle
Add Loki as a data source in Grafana (type Loki, URL http://loki:3100) and open Explore.
Every LogQL query starts with a stream selector in {}, then a pipeline of stages joined by |.
Filter lines
{container="hotrod"} |= "ERROR"
|= keeps lines that contain the text, != drops them, |~ and !~ take a regex. Here is that
query on the lab, after a few ride requests to HotROD:
The raw lines, straight from Loki's API:
2026-11-04T04:43:50.771Z ERROR driver/server.go:78 Retrying GetDriver after error {"service": "driver", "trace_id": "2b808cbcdff851ae999d49dd531d662d", "span_id": "86315083e8a2fe58", "retry_no": 1, "error": "redis timeout"} 2026-11-04T04:43:50.771Z ERROR driver/redis.go:79 redis timeout {"service": "driver", "trace_id": "2b808cbcdff851ae999d49dd531d662d", "span_id": "aaf6b22d4ce0fd1a", "driver_id": "T718238C", "error": "redis timeout"}
The driver service timed out talking to Redis and retried. Note the trace_id: the next lesson
uses it to see the whole request.
Parse fields, and a real gotcha
These lines have a timestamp, a level and a caller, then a JSON part. The obvious parser fails:
{container="hotrod"} | json
stream {'__error__': 'JSONParserErr', '__error_details__': "Value looks like object, but can't find closing '}' symbol", 'container': 'hotrod', ...}
json needs the whole line to be JSON. When a parser fails, Loki keeps the line and adds an
__error__ label instead of hiding it. For this mixed format, describe the line's shape with the
pattern parser:
{container="hotrod"} | pattern "<ts>\t<level>\t<caller>\t<msg>\t<fields>" | level="ERROR" | line_format "{{.ts}} {{.caller}} {{.msg}}"
2026-11-04T04:43:50.771Z driver/redis.go:79 redis timeout 2026-11-04T04:43:50.692Z driver/redis.go:79 redis timeout 2026-11-04T04:43:50.693Z driver/server.go:78 Retrying GetDriver after error
pattern turns each <name> into a field you can filter on (level="ERROR"), and line_format
rewrites the line to only what you care about. If you control the app, log pure JSON, one
object per line, and | json just works.
Turn logs into numbers
Wrap a log query in a range function and you get a metric, just like PromQL:
sum by (container) (count_over_time({host="lab-1"}[5m]))
{'container': 'alertmanager'} 1 {'container': 'alloy'} 26 {'container': 'grafana'} 96 {'container': 'hotrod'} 145 {'container': 'jaeger'} 43 {'container': 'loki'} 120 {'container': 'node-exporter'} 20 {'container': 'prometheus'} 4
sum by (level) (count_over_time({container="hotrod"} | pattern "<_>\t<level>\t<_>" [15m]))
{'level': 'ERROR'} 36 {'level': 'INFO'} 306
36 errors in 15 minutes, about 10% of HotROD's lines. count_over_time, rate and bytes_over_time
are the ones you'll use most. A Loki ruler can run expressions like these as alert rules and
send them to the same Alertmanager as lesson 4.
Elastic Stack, Graylog and Splunk
Loki isn't the only answer. All of these do the same job (agents ship logs, a store keeps them, a UI searches them). They differ in how they index, and so in cost and speed.
| Tool | How it stores and searches | Good at | Watch out for |
|---|---|---|---|
| Grafana Loki | Indexes labels only; lines in compressed chunks on object storage | Cheap storage, same Grafana as metrics and traces, LogQL like PromQL | Slow "search everything for one word"; label discipline needed |
| Elastic Stack (Elasticsearch, Logstash or Beats, Kibana) | Indexes every field and word | Fast full-text search, rich aggregations, security analytics | Needs much more storage and memory; running clusters is real work |
| Graylog | Uses OpenSearch or Elasticsearch underneath, adds its own server and UI | Simple setup for log management, streams and alerts, role-based access | Still runs the search cluster underneath |
| Splunk | Commercial platform, indexes everything, SPL query language | Powerful search, compliance and security teams, huge app ecosystem | Licence priced by data volume; costs grow quickly |
A rough rule: if your team already uses Prometheus and Grafana and mostly asks "show me errors from service X between these times", Loki is the cheapest good answer. If people need to search any word across all logs fast, or the security team needs a SIEM, the Elastic Stack or Splunk earns its cost.
Centralising logs also centralises every password, token, card number and email address that
leaked into a log line. Mask them in the app or in the agent (Alloy's loki.process can drop or
replace fields) before they're shipped, and set a retention period, for example 30 days.
Run Loki in its scalable mode with chunks in object storage (S3 or GCS) and set
retention_period. Deploy Alloy as a DaemonSet on Kubernetes or a systemd service on servers. Keep
labels to a handful (cluster, namespace, app, host, level) and put trace IDs in the line so logs
link to traces.
Hunt an error across services
With Loki, Alloy and HotROD running, send a few requests to HotROD, then use LogQL to answer: Which service logged errors? What was the error message? How many errors in the last 15 minutes? Which trace_id does one of the errors belong to? Save each query and its answer.
~/log-hunt.txtReveal one safe solution
$ for c in 123 392 731 567; do curl -s -o /dev/null "localhost:8080/dispatch?customer=$c"; done $ Q() { curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode "query=$1" --data-urlencode since=15m; } $ Q '{container="hotrod"} |= "ERROR"' >> ~/log-hunt.txt $ Q 'sum by (level) (count_over_time({container="hotrod"} | pattern "<_>\t<level>\t<_>" [15m]))' >> ~/log-hunt.txt
for c in 123 392 731 567; do curl -s -o /dev/null "localhost:8080/dispatch?customer=$c"; doneforloop over a listdostart of what the loop runs each timecurlmake an HTTP request-ssilent: no progress bar-owrite the body to this filedoneend of the loop
Q '{container="hotrod"} |= "ERROR"' >> ~/log-hunt.txt>>append output to a file
On the lab, every error came from the driver service with redis timeout, there were 36 in 15
minutes, and each line carried a trace_id such as 2b808cbcdff851ae999d49dd531d662d. Keep that ID:
the tracing lesson opens it in Jaeger.
Try it yourself
0 of 6 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
What does Loki index?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.