# 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.

Course: [Monitoring](https://devops.rajeev.pro/courses/monitoring), lesson 5. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/monitoring/05-centralised-logs

## What you will learn

- Explain why logs belong in a central store, and what an agent does
- Describe how Loki indexes labels instead of words, and why labels must stay few
- Ship container logs to Loki with Grafana Alloy
- Write LogQL that selects streams, filters lines, parses fields and counts errors
- Compare Loki with the Elastic Stack, Graylog and Splunk, and pick one for a team

When 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.

> **Video.** [Meet Grafana LOKI, a Log Aggregation System for EVERYTHING](https://www.youtube.com/watch?v=h_GGd7HfKQ8) (Techno Tim)

## How Loki stores logs

> **Figure.** Three sources on the left: web-1 writing /var/log/nginx/access.log, web-2 writing to journald, and a checkout pod writing to stdout, each with a Grafana Alloy agent. Arrows go to Loki, which indexes labels not words: a stream is one set of labels such as job nginx host web-1; the index maps labels to chunks, and chunks hold the compressed lines in S3, GCS or local disk. On the right, Grafana Explore runs a LogQL query filtering errors, parsing JSON and keeping status 500 and above, and a Loki ruler rule can alert on log counts through Alertmanager.
>
> Alloy reads and labels the logs, Loki stores them, Grafana searches them.

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:

1. It finds the stream from the labels, creating a new one if this label set is new.
2. It appends the lines to that stream's current **chunk** and compresses it.
3. 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:

```logql
{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.

```sh
$ 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
```

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:

```alloy
// 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:

1. `discovery.docker` asks the Docker socket for every container.
2. `discovery.relabel` holds one rule: take the container name (Docker reports it as `/hotrod`),
   strip the slash, and store it as the label `container`.
3. `loki.source.docker` reads each container's output, applies those rules, adds `host="lab-1"`,
   and forwards the lines.
4. `loki.write` pushes batches to Loki's HTTP API.

```sh
$ 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
```

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:

> **Figure.** The Grafana Alloy Pipeline page. discovery.docker containers and discovery.relabel containers both feed targets into loki.source.docker containers, which sends logs to loki.write local.
>
> Alloy's graph view: two discovery components feed the Docker log source, which sends logs to loki.write.

Within a few seconds Loki knows about every container:

```sh
$ 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"]}
```

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.

> **Promtail is retired.** 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

```logql
{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:

> **Figure.** Grafana Explore with the Loki data source and the query container hotrod, line contains ERROR, over the last 15 minutes. A logs volume chart shows red error bars in bursts, 66 in total. Below, 66 log lines such as an ERROR from driver/server.go:78, Retrying GetDriver after error, with a JSON part containing service driver, a trace_id, a span_id, retry_no 1 and error redis timeout.
>
> Real errors from the demo app: Redis timeouts in the driver service, each line carrying the trace_id of the request that hit it.

The raw lines, straight from Loki's API:

```text
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:

```logql
{container="hotrod"} | json
```

```text
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:

```logql
{container="hotrod"}
  | pattern "<ts>\t<level>\t<caller>\t<msg>\t<fields>"
  | level="ERROR"
  | line_format "{{.ts}} {{.caller}} {{.msg}}"
```

```text
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:

```logql
sum by (container) (count_over_time({host="lab-1"}[5m]))
```

```text
{'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
```

```logql
sum by (level) (count_over_time({container="hotrod"} | pattern "<_>\t<level>\t<_>" [15m]))
```

```text
{'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.

> **Logs are personal data.** 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.

> **In production.** 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.

## Mission: 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.

- You need: curl 'localhost:8080/dispatch?customer=123'
- You'll have: ~/log-hunt.txt

```sh
$ 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
```

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

- Start Loki and run `curl -s localhost:3100/ready`.
- Run Alloy with the config from this lesson and list labels with `curl -s localhost:3100/loki/api/v1/labels`.
- In Grafana Explore, run `{container="hotrod"} |= "ERROR"` and read one line.
- Count lines per container over 5 minutes with `sum by (container) (count_over_time({host="lab-1"}[5m]))`.
- Run `{container="hotrod"} | json`, read the `__error__` label, then fix it with `pattern`.
- Do the mini mission and keep `~/log-hunt.txt`.

## Quiz

1. What does Loki index?
   - Every word in every log line
   - **Only the labels of each stream; the lines are stored compressed and searched when queried** (answer)
   - Nothing, it is a plain file server
   Why: Loki indexes the small set of labels (job, host, container) and stores the lines in compressed chunks. That's why it's cheap to run, and why label choice matters so much.

2. Why should a user ID never be a Loki label?
   - Labels can't contain numbers
   - **Every distinct label value creates a new stream, so millions of users means millions of tiny streams and a slow, expensive index** (answer)
   - Loki deletes labels after an hour
   Why: High-cardinality labels explode the number of streams. Keep the user ID in the log line and filter for it with |= or a parser.

3. `{container="hotrod"} | json` returns lines with `__error__="JSONParserErr"`. Why?
   - Loki can't parse JSON at all
   - **The lines start with a timestamp and level before the JSON part, so the whole line isn't valid JSON** (answer)
   - The container label is wrong
   Why: The json parser needs the whole line to be JSON. Use the pattern or regexp parser for mixed formats, or make the app log pure JSON.

4. In LogQL, what is the difference between `{app="api"} |= "timeout"` and `count_over_time({app="api"} |= "timeout" [5m])`?
   - There is none
   - **The first returns matching lines; the second returns a number per stream, usable on a graph or in an alert** (answer)
   - The second is faster but less accurate
   Why: Wrapping a log query in a range function such as count_over_time turns lines into a metric, which you can graph, sum by label or alert on.

5. A team needs fast full-text search across all logs, complex aggregations and has budget for storage. Which fits best?
   - Loki
   - **The Elastic Stack (Elasticsearch, Logstash or Beats, Kibana)** (answer)
   - node_exporter
   Why: Elasticsearch indexes every word, so full-text search over everything is fast, at the cost of more storage and more operations work. Loki is cheaper when you mostly filter by service and time.

## Resources

- [Grafana Loki documentation](https://grafana.com/docs/loki/latest/) (Grafana Labs)
- [LogQL log queries](https://grafana.com/docs/loki/latest/query/log_queries/) (Grafana Labs)
- [Label best practices (cardinality)](https://grafana.com/docs/loki/latest/get-started/labels/bp-labels/) (Grafana Labs)
- [Grafana Alloy documentation](https://grafana.com/docs/alloy/latest/) (Grafana Labs)
- [loki.source.docker component](https://grafana.com/docs/alloy/latest/reference/components/loki/loki.source.docker/) (Grafana Labs)
- [Elastic Stack overview](https://www.elastic.co/elastic-stack) (Elastic)
- [Graylog documentation](https://go2docs.graylog.org/current/home.htm) (Graylog)
