LogQL: Filtering & Parsing
LogQL is Loki's query language, designed to feel like PromQL. A log query is a stream selector followed by a pipeline of stages separated by |:
{app="linkly", env="prod"} |= "create link" | json | status >= 500 | line_format "{{.pod}} {{.error}}"
└──── stream selector ───┘ └─line filter─┘ └parser┘ └label filter┘ └──── formatting ────────┘Loki picks the streams with the selector (using its index), then runs every line of those streams through the pipeline. The cheapest stages go first: label selectors cut whole streams, line filters are fast substring scans, parsers are the expensive part.
| Stage | Examples |
|---|---|
| stream selector | {app="linkly"}, `{namespace=~"links |
| line filter | ` |
| parser | ` |
| label filter | ` |
| formatting | ` |
Parsers turn fields of the line into temporary labels for the rest of the pipeline (nested JSON fields become cache_hit for {"cache":{"hit":…}}). Numeric comparisons work on them directly; durations and byte sizes too (| latency > 250ms, | size > 1MB).
Running queries
The session loads two minutes of linkly logs (generated with fixed timestamps) into Loki and queries them. The Loki config is the one from the previous lesson:
cat > loki.yaml <<'YML'
auth_enabled: false
server: {http_listen_address: 127.0.0.1, http_listen_port: 3100, grpc_listen_address: 127.0.0.1, log_level: error}
common:
path_prefix: /home/learner/loki
instance_addr: 127.0.0.1
replication_factor: 1
ring: {kvstore: {store: inmemory}}
storage: {filesystem: {chunks_directory: /home/learner/loki/chunks, rules_directory: /home/learner/loki/rules}}
schema_config:
configs:
- {from: 2020-01-01, store: tsdb, object_store: filesystem, schema: v13, index: {prefix: index_, period: 24h}}
limits_config: {reject_old_samples: false}
ingester: {max_chunk_age: 87600h, chunk_idle_period: 87600h, lifecycler: {min_ready_duration: 0s}}
querier: {query_ingesters_within: 87600h}
analytics: {reporting_enabled: false}
YML
loki -config.file=loki.yaml >loki.log 2>&1 &
for i in $(seq 150); do [ "$(curl -s 127.0.0.1:3100/ready)" = ready ] && break; sleep 0.2; done
python3 - > push.json <<'PY'
import json, random
random.seed(5)
start = 1767261600 # 2026-01-01T10:00:00Z
streams = {}
for s in range(120): # one line per second for two minutes
pod = f"linkly-{s % 2}"
r = random.random()
if r < 0.06:
rec = {"level": "ERROR", "msg": "create link failed", "route": "/links", "status": 500,
"duration_ms": 2000 + random.randrange(10), "error": "statement timeout",
"trace_id": f"{random.getrandbits(64):016x}"}
elif r < 0.2:
rec = {"level": "INFO", "msg": "link created", "route": "/links", "status": 201, "duration_ms": 10 + random.randrange(20)}
elif r < 0.27:
rec = {"level": "WARN", "msg": "slow redirect", "route": "/{code}", "status": 302,
"duration_ms": 300 + random.randrange(400), "cache": {"hit": False}}
else:
rec = {"level": "INFO", "msg": "redirect", "route": "/{code}", "status": random.choice([302, 302, 302, 404]),
"duration_ms": 2 + random.randrange(8), "cache": {"hit": True}}
streams.setdefault(pod, []).append([str((start + s) * 10**9), json.dumps(rec, separators=(",", ":"))])
print(json.dumps({"streams": [{"stream": {"app": "linkly", "env": "prod", "pod": p}, "values": v}
for p, v in sorted(streams.items())]}))
PY
curl -s -H 'Content-Type: application/json' --data @push.json 127.0.0.1:3100/loki/api/v1/push
q() { echo "> $1"; logcli query --quiet -o raw --limit=10 --forward \
--from=2026-01-01T10:00:00Z --to=2026-01-01T10:05:00Z "$1"; }
q '{app="linkly"} |= "statement timeout" | json | line_format "{{.pod}} {{.duration_ms}}ms trace={{.trace_id}}"'
q '{app="linkly"} | json | status >= 400 and status < 500 | line_format "{{.pod}} {{.status}} {{.route}}"'
q '{app="linkly", pod="linkly-1"} | json | duration_ms > 500 | line_format "{{.level}} {{.msg}} {{.duration_ms}}ms"'
q '{app="linkly"} | json | cache_hit = "false" | keep pod | line_format "{{.pod}} cache miss"'> {app="linkly"} |= "statement timeout" | json | line_format "{{.pod}} {{.duration_ms}}ms trace={{.trace_id}}"
linkly-1 2006ms trace=ef901b932a7c1880
linkly-1 2002ms trace=f486ab739faba827
linkly-1 2002ms trace=513de7811c5f4755
linkly-0 2006ms trace=474d9d8ef3bd423e
linkly-0 2009ms trace=71871853f5f90414
linkly-1 2002ms trace=4847ec0e4cfa0116
linkly-1 2008ms trace=af8c30a074a319dc
> {app="linkly"} | json | status >= 400 and status < 500 | line_format "{{.pod}} {{.status}} {{.route}}"
linkly-1 404 /{code}
linkly-0 404 /{code}
linkly-1 404 /{code}
linkly-1 404 /{code}
linkly-0 404 /{code}
linkly-1 404 /{code}
linkly-0 404 /{code}
linkly-0 404 /{code}
linkly-1 404 /{code}
linkly-1 404 /{code}
> {app="linkly", pod="linkly-1"} | json | duration_ms > 500 | line_format "{{.level}} {{.msg}} {{.duration_ms}}ms"
ERROR create link failed 2006ms
ERROR create link failed 2002ms
WARN slow redirect 604ms
ERROR create link failed 2002ms
ERROR create link failed 2002ms
ERROR create link failed 2008ms
> {app="linkly"} | json | cache_hit = "false" | keep pod | line_format "{{.pod}} cache miss"
linkly-1 cache miss
linkly-1 cache miss
linkly-1 cache miss
linkly-1 cache miss
What each query shows:
- A substring filter first (
|= "statement timeout"is fast), thenjsonto pull outpod,duration_msandtrace_idfor a compact view. The trace id is what you'd click to open the trace. - A numeric range on the parsed
status: the 404s, which come from redirects for unknown codes. Exactly ten lines came back: that is--limit=10, not the total. podis a stream label, so{…, pod="linkly-1"}narrows before scanning;duration_ms > 500keeps slow requests of both kinds (failed creations and slow redirects).- Nested JSON fields are flattened with
_:{"cache":{"hit":false}}becomescache_hit. Parsed values are strings, so the comparison is with"false".
-o raw prints only the (formatted) line; --limit caps the number of lines (Loki's default limit for Grafana is 1,000 lines, so "no more errors" in a panel can just mean "limit reached").
Other parsers
# logfmt lines: level=error msg="db timeout" duration=2.003s
{app="legacy"} | logfmt | level="error" | duration > 1s
# nginx access log with pattern (named captures, <_> to skip)
{app="ingress"} | pattern `<ip> - - [<_>] "<method> <path> <_>" <status> <bytes> <_> "<agent>"` | status >= 500
# only some JSON fields (cheaper on big lines)
{app="linkly"} | json status, ms="duration_ms" | ms > 1000Parsing errors don't drop the line: Loki adds a __error__ label (JSONParserErr), which you can filter with | __error__ = "" to keep only parseable lines, or the opposite to find broken ones.
Writing fast queries
- Narrow the stream selector as much as possible (namespace, app, env); it's the only indexed step.
- Put line filters before parsers:
|= "ERROR" | json | …scans for a substring before paying for JSON parsing. - Keep the time range short; Loki cost grows with the bytes scanned in it.
- Use structured metadata (
| trace_id = "…") for IDs instead of regex over lines.
Test yourself
Which part of a LogQL query uses Loki's index?
- The line filter
- The stream selector in braces
- The json parser
- line_format
What label name does | json give the field {"cache": {"hit": false}}?
cache.hitcache_hithitcache
Why write |= "timeout" | json rather than | json | error =~ ".*timeout.*"?
- Same cost
- The substring filter discards most lines before the expensive JSON parsing
- json can't follow a filter
- Regex isn't allowed