Skip to main content

Data and monitoring · Intermediate · 24 min

Search and count logs with LogQL

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Loki 3.7.10 · logcli 3.7.10

You will push JSON and logfmt logs into a practice Loki 3.7, then use logcli to filter them, parse their fields, reformat lines and turn them into counts, rates and a p95 latency.

On this page

Loki stores logs as streams. A stream is every line that shares one set of labels, such as {job="shop-api", host="web-1"}. Loki indexes only those labels, not the text of the lines, which is why it is cheap to run. The price is that you search the text at query time, and LogQL is how you do it.

A LogQL query has two parts. The stream selector in curly braces picks which streams to read, using the index. Everything after it is a pipeline that runs over each line: keep lines that contain a word, parse the line into fields, keep lines where a field has some value, rewrite the line. Wrap the whole thing in a function such as count_over_time and the result is no longer lines but numbers, the same kind you graph and alert on in Prometheus.

In this tutorial you run a small practice Loki on port 3101, push 18 lines from a made-up shop (an API that logs JSON and a background worker that logs logfmt), and query them with logcli, Loki's command-line client. Because you know exactly what went in, you can check every answer by counting. The practice Loki uses its own port and folder, so it does not mix with a Loki you may already run on port 3100 from the Loki and Grafana Alloy tutorial.

Step 1 · Download Loki and logcli

Install the tools, then download both programs from the Loki 3.7.10 release, with the checksum list from the same release. The checksum check catches a damaged or cut-off download; download only from the official GitHub release address, because the list comes from the same place:

Bash
sudo apt update
sudo apt install -y curl ca-certificates unzip jq
mkdir -p ~/logql-demo/bin
cd ~/logql-demo
LOKI_VERSION=3.7.10
ARCH="$(dpkg --print-architecture)"
BASE="https://github.com/grafana/loki/releases/download/v${LOKI_VERSION}"
curl -fsSLO "${BASE}/loki-linux-${ARCH}.zip"
curl -fsSLO "${BASE}/logcli-linux-${ARCH}.zip"
curl -fsSLO "${BASE}/SHA256SUMS"
sha256sum --ignore-missing -c SHA256SUMS

The last command prints two lines ending in OK, one for each zip file. dpkg --print-architecture gives amd64 on most machines and arm64 on ARM ones, which match the release file names. The two files are large (over 100 MB each unpacked), so on a metered or prepaid connection download them once and keep the zips.

Unpack them into the demo folder and put that folder first on your PATH for this terminal:

Bash
unzip -o "loki-linux-${ARCH}.zip"
unzip -o "logcli-linux-${ARCH}.zip"
install -m 0755 "loki-linux-${ARCH}" bin/loki
install -m 0755 "logcli-linux-${ARCH}" bin/logcli
rm "loki-linux-${ARCH}" "logcli-linux-${ARCH}"
export PATH="$HOME/logql-demo/bin:$PATH"
loki -version | head -n 1
logcli --version 2>&1 | head -n 1

Check it worked

The two version lines start with loki, version 3.7.10 and logcli, version 3.7.10. If you open a new terminal later, run the export PATH=... line again there.

These are hand-installed programs: apt upgrade never updates them. For a practice copy that does not matter, because you delete it at the end. For a Loki you keep, follow the upgrade advice in the Loki and Grafana Alloy tutorial.

Step 2 · Start a practice Loki

Write a small configuration. It keeps everything in ~/logql-demo/data, listens on 127.0.0.1 only, and turns off the anonymous usage report Loki sends by default. The heredoc is unquoted on purpose, so the shell fills in your home folder:

Bash
mkdir -p ~/logql-demo/data
cat > ~/logql-demo/loki.yaml <<EOF
auth_enabled: false

server:
  http_listen_address: 127.0.0.1
  http_listen_port: 3101
  grpc_listen_address: 127.0.0.1
  grpc_listen_port: 9097

common:
  instance_addr: 127.0.0.1
  path_prefix: $HOME/logql-demo/data
  storage:
    filesystem:
      chunks_directory: $HOME/logql-demo/data/chunks
      rules_directory: $HOME/logql-demo/data/rules
  replication_factor: 1
  ring:
    kvstore:
      store: inmemory

schema_config:
  configs:
    - from: 2024-01-01
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h

memberlist:
  bind_port: 7947

analytics:
  reporting_enabled: false
EOF
grep -n 'path_prefix' ~/logql-demo/loki.yaml

The grep shows path_prefix: followed by your real home folder, such as /home/you/logql-demo/data, not the text $HOME.

In your second terminal, start Loki in the foreground. Leave it running; its own log scrolls past in that window:

Bash
~/logql-demo/bin/loki -config.file="$HOME/logql-demo/loki.yaml"

Check it worked

Back in the first terminal, ask Loki whether it is ready:

Bash
curl -s http://127.0.0.1:3101/ready

It prints ready. For the first 15 seconds or so it prints a line such as Ingester not ready: waiting for 15s after being ready instead; wait and run it again. If the second terminal shows address already in use, another program has port 3101, 9097 or 7947: change the three port numbers in loki.yaml and in the commands below.

Step 3 · Push sample logs and look at their labels

Create the two log files. The API writes one JSON object per line, the way structlog or Pino would. The worker writes logfmt, key=value pairs separated by spaces:

Bash
cd ~/logql-demo
cat > api.jsonl <<'EOF'
{"level":"info","method":"GET","path":"/products","status":200,"duration_ms":42,"user":"ada","msg":"listed products"}
{"level":"info","method":"GET","path":"/products","status":200,"duration_ms":38,"user":"bola","msg":"listed products"}
{"level":"info","method":"POST","path":"/checkout","status":201,"duration_ms":310,"user":"ada","msg":"order placed"}
{"level":"warn","method":"GET","path":"/products","status":200,"duration_ms":950,"user":"chidi","msg":"slow database query"}
{"level":"error","method":"POST","path":"/checkout","status":502,"duration_ms":1200,"user":"bola","msg":"payment gateway timeout"}
{"level":"info","method":"GET","path":"/cart","status":200,"duration_ms":25,"user":"ada","msg":"showed cart"}
{"level":"info","method":"POST","path":"/checkout","status":201,"duration_ms":280,"user":"chidi","msg":"order placed"}
{"level":"error","method":"POST","path":"/checkout","status":500,"duration_ms":45,"user":"dami","msg":"basket empty"}
{"level":"info","method":"GET","path":"/products","status":200,"duration_ms":51,"user":"dami","msg":"listed products"}
{"level":"debug","method":"GET","path":"/health","status":200,"duration_ms":2,"user":"","msg":"health check"}
{"level":"debug","method":"GET","path":"/health","status":200,"duration_ms":3,"user":"","msg":"health check"}
{"level":"info","method":"GET","path":"/cart","status":404,"duration_ms":18,"user":"bola","msg":"cart not found"}
EOF
cat > worker.logfmt <<'EOF'
level=info task=send_email order=1001 took=0.8s msg="receipt sent"
level=info task=send_email order=1002 took=1.1s msg="receipt sent"
level=error task=charge_card order=1003 took=4.2s msg="gateway timeout"
level=info task=charge_card order=1004 took=0.9s msg="card charged"
level=warn task=send_email order=1005 took=2.5s msg="retrying smtp"
level=info task=resize_image order=1006 took=0.3s msg="thumbnail made"
EOF
wc -l api.jsonl worker.logfmt

wc counts 12 and 6 lines.

Normally a collector such as Grafana Alloy tails files and sends them to Loki. Here a short script does the same job through Loki's push API, so you can see what a push is: a JSON body with the stream's labels and a list of [timestamp, line] pairs. Timestamps are nanoseconds since 1970, as strings. The script spaces the lines one second apart, starting a few minutes ago:

Bash
cat > push-logs.sh <<'EOF'
#!/usr/bin/env bash
# Usage: push-logs.sh <file> <job> <host> <seconds ago>
set -euo pipefail
file="$1" job="$2" host="$3" ago="$4"
jq -Rs --arg job "$job" --arg host "$host" --argjson start "$(( $(date +%s) - ago ))" '
  {streams: [{
    stream: {job: $job, host: $host, env: "demo"},
    values: (split("\n") | map(select(length > 0)) | to_entries
             | map(["\($start + .key)000000000", .value]))
  }]}' "$file" |
  curl -fsS -H 'Content-Type: application/json' --data-binary @- \
    "${LOKI_ADDR:-http://127.0.0.1:3101}/loki/api/v1/push"
echo "pushed $(grep -c . "$file") lines from $file"
EOF
chmod +x push-logs.sh
export LOKI_ADDR=http://127.0.0.1:3101
./push-logs.sh api.jsonl shop-api web-1 300
./push-logs.sh worker.logfmt shop-worker worker-1 240

Each push prints pushed 12 lines from api.jsonl and pushed 6 lines from worker.logfmt. Loki answers a good push with an empty 204 No Content, so curl itself prints nothing. logcli reads LOKI_ADDR to find the server, which is why you exported it; set it again in any new terminal.

Now list the streams Loki holds for env="demo":

Bash
logcli series --quiet '{env="demo"}'
logcli series --quiet --analyze-labels '{env="demo"}'

The first command prints two streams, something like {env="demo", host="web-1", job="shop-api", service_name="shop-api"} and the same for shop-worker. Loki adds service_name itself, copied from job when a stream has no service name. The second prints a short table: how many distinct values each label has across these streams.

Keep labels few, let fields be many

Every distinct combination of label values is a separate stream, with its own index entries and its own chunk files. Labels with a handful of values, such as job, host, env or level, are cheap. A label holding a user name, an order number or a request id creates a new stream for almost every line, and Loki slows down and runs out of memory long before you run out of disk. The rule: a label should answer "which program and where", and should have tens of values, not thousands.

Everything else stays in the line as a field. user, path, status and duration_ms are not labels here, yet in the next steps you filter and group on every one of them, because the parsers turn fields into labels for the length of one query only.

Check it worked

logcli series shows exactly two streams, and --analyze-labels shows no label with more than two values. Run logcli labels to see the label names Loki indexes: env, host, job and service_name, with no user or status.

Step 4 · Filter by stream and by text

The stream selector chooses streams by label. Line filters then keep or drop lines by their text: |= contains, != does not contain, |~ matches a regular expression and !~ does not. Line filters are the cheapest part of a query, so put them first. -o raw prints only the line text, without timestamps and labels:

Bash
logcli query --quiet -o raw '{job="shop-api"}' | wc -l
logcli query --quiet -o raw '{job="shop-api"} |= "/checkout"'
logcli query --quiet -o raw '{job="shop-api"} != "/health"' | wc -l
logcli query --quiet -o raw '{job="shop-api"} |~ "timeout|empty"'

logcli query looks back one hour by default (--since 1h) and prints at most 30 lines (--limit 30, or --limit 0 for all). Newest lines come first.

Check it worked

You get 12, then the four /checkout lines, then 10 (the two health checks are gone), then the two lines whose message is basket empty or payment gateway timeout. Selecting both jobs at once with '{env="demo"}' gives all 18 lines.

A text match is blunt: |= "500" would also match a duration of 500 ms or an order number 1500. To ask about a field, parse first.

Step 5 · Parse JSON and logfmt, then filter on fields

| json turns each top-level key of a JSON line into a temporary label. | logfmt does the same for key=value lines. After a parser you can write label filters, and numbers and durations compare as numbers, not text:

Bash
logcli query --quiet -o raw '{job="shop-api"} | json | status >= 500'
logcli query --quiet -o raw '{job="shop-api"} | json | path="/checkout" and duration_ms > 300'
logcli query --quiet -o raw '{job="shop-worker"} | logfmt | took > 2s'
logcli query --quiet -o raw '{job="shop-worker"} | logfmt | task="send_email"' | wc -l

The first query returns the 502 and 500 lines. The second returns the two checkouts that took 310 ms and 1200 ms, but not the one at 280 ms. The third compares took as a duration and returns orders 1003 (4.2s) and 1005 (2.5s). The fourth counts 3 email tasks.

When a parser fails on a line, Loki does not drop it. It adds a label __error__ instead. Run the JSON parser over both jobs and keep only the failures:

Bash
logcli query --quiet -o raw '{env="demo"} | json | __error__!=""' | wc -l

Check it worked

The last command prints 6: every worker line, because logfmt is not JSON. In your own queries, add | __error__="" after a parser when a stream mixes formats, so a filter such as status >= 500 only sees lines that parsed.

Step 6 · Reformat lines for reading

A JSON line suits programs and tires people. line_format replaces each line with a template, using Go template syntax, where {{.name}} is any label or parsed field. Show the API errors as one short sentence each:

Bash
logcli query --quiet -o raw '{job="shop-api"} | json | level="error" | line_format "{{.method}} {{.path}} {{.status}} {{.duration_ms}}ms {{.msg}}"'

This changes only what the query returns; the stored line is untouched. Messages in other languages and scripts, such as Yoruba or Amharic text in a msg field, come through unchanged, because Loki stores and returns lines as UTF-8.

Check it worked

You get exactly these two lines, newest first:

Text
POST /checkout 500 45ms basket empty
POST /checkout 502 1200ms payment gateway timeout

Step 7 · Turn logs into counts and rates

Wrap a log query in a range function and Loki returns numbers instead of lines. count_over_time(... [15m]) counts matching lines in the last 15 minutes, per stream. sum by (level) adds those counts up per value of a field. These are metric queries, so use logcli instant-query, which evaluates them once, now, and prints the result as JSON; jq turns that into one line per group:

Bash
logcli instant-query --quiet 'sum by (level) (count_over_time({job="shop-api"} | json [15m]))' |
  jq -r '.[] | "\(.metric.level) \(.value[1])"' | sort

rate is the count divided by the window in seconds. Here it is the rate of server errors per second:

Bash
logcli instant-query --quiet 'sum(rate({job="shop-api"} | json | status >= 500 [15m]))' |
  jq -r '.[0].value[1]'

The window must cover the time your lines arrived. The sample lines are a few minutes old, so [15m] catches all of them; if you come back to this step later than 15 minutes after pushing, run the two ./push-logs.sh commands again first, or use a longer window.

Check it worked

The first query prints debug 2, error 2, info 7 and warn 1, which add up to the 12 lines. The second prints about 0.00222: two errors in 900 seconds. That small number is what an alert rule or a Grafana panel would track, and for someone checking a dashboard from a phone on mobile data, a few numbers cost far less to load than thousands of raw lines.

Step 8 · Measure latency with unwrap

Counting lines tells you how often; unwrap tells you how much. It takes a numeric field from each line and uses it as the sample value, so functions such as quantile_over_time, avg_over_time and max_over_time work on it. Find the 95th percentile of checkout time:

Bash
logcli instant-query --quiet 'quantile_over_time(0.95, {job="shop-api"} | json | path="/checkout" | __error__="" | unwrap duration_ms [15m]) by (path)' |
  jq -r '.[] | "\(.metric.path) \(.value[1])"'

The by (path) matters. Without it, every other parsed field, such as user and status, stays on the result, and you get one tiny series per combination instead of one answer.

For a field written as a duration, such as the worker's took=4.2s, unwrap duration(took) converts it to seconds first. This gives the slowest run of each task:

Bash
logcli instant-query --quiet 'max_over_time({job="shop-worker"} | logfmt | unwrap duration(took) [15m]) by (task)' |
  jq -r '.[] | "\(.metric.task) \(.value[1])"' | sort

Check it worked

The first query prints /checkout 1066.5. You can check it by hand: the four checkout times sorted are 45, 280, 310 and 1200 ms; the 95th percentile sits 0.95 × 3 = 2.85 places along, so it is 310 plus 0.85 of the gap to 1200. With only four values that is mostly the slowest one, which is the honest answer from so little data. The second query prints charge_card 4.2, resize_image 0.3 and send_email 2.5.

Step 9 · Stop Loki and remove the demo

Press Ctrl+C in the second terminal to stop Loki. It takes a few seconds to flush and exit. Then check the port is free and delete the demo folder, which holds the programs, the zips, the configuration and the stored logs. If you want to keep logcli for your own Loki, copy it out first with sudo install -m 0755 ~/logql-demo/bin/logcli /usr/local/bin/logcli, because the rm below deletes it:

Bash
curl -s --connect-timeout 1 http://127.0.0.1:3101/ready || echo "Loki has stopped"
rm -rf ~/logql-demo
unset LOKI_ADDR

Check it worked

The first command prints Loki has stopped, and ls ~/logql-demo reports No such file or directory. If you kept logcli, set LOKI_ADDR to your own Loki's address, such as http://127.0.0.1:3100, before you use it again.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.