Pcornel
Browse topics
Options
Recent
Favorites
Observability · Technical reference

LogQL Queries in Loki

Direct answer

LogQL is Loki's query language: a stream selector {app="api"}, line filters |= "error", parsers | json, and metric queries such as rate({...}[5m]).

When to use this

Use it to search and aggregate logs in Loki.

First 30 seconds

1. Search: {app="api"} |= "error" | json | status >= 500.

2. Rate: sum by (status)(rate({app="api"} | json [5m])).

3. Narrow time range.

4. Use logcli for scripts: logcli query '{app="api"}'.

5. Check query stats.

Operational verification

stream selector → line filters → parser → label filters → aggregation

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
OpenTelemetry / Prometheus / Grafana / common metrics-log-trace pipelines
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformOpenTelemetry / Prometheus / Grafana / common metrics-log-trace pipelines
Scope / prerequisiteUse it to search and aggregate logs in Loki.
What next?2 suggested next steps
Evidence0
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

2 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 How to verify Verify boundary

Compare a log-based count with the application's own metric. Check query statistics for bytes scanned.

Step 2 Common failures Narrow the fault

Broad selectors over long time ranges scan huge amounts of data. Parsing JSON without a line filter first is slow. Using high-cardinality values as labels harms ingestion.

Key points

Always start with a narrow stream selector (indexed labels). Filter lines before parsing. Don't make high-cardinality labels; filter extracted fields at query time.

Key checks
  • {app="api"} |= "error" | json | status >= 500 — first check for this topic
  • curl -s localhost:9090/-/ready — Prometheus ready
  • curl -s 'localhost:9090/api/v1/query?query=up' — scrape targets up/down
  • promtool check config prometheus.yml — config valid
ReferenceWhat it is1 section · depth on demand

How it works

Loki indexes only labels; it scans the chunks of the selected streams for line content. Narrow label selectors and time ranges keep queries cheap. Metric queries turn log lines into time series.

ReferenceImportant terms & boundaries3 sections · depth on demand

LogQL examples

{app="checkout", env="prod"} |= "error"
{app="checkout"} | json | status >= 500 | line_format "{{.method}} {{.path}} {{.status}}"
sum by (status) (rate({app="checkout"} | json [5m]))
topk(5, sum by (path) (count_over_time({app="web"} | logfmt | duration > 1s [10m])))

Stream selectors (labels) must be selective; Loki indexes labels, not log content, so keep labels low-cardinality and filter content with |=, |~ and parsers.

In depth

How Loki executes a query

Loki indexes only the labels of a stream. A query first selects streams by label, then reads and filters their compressed log chunks for the time range. Cost therefore grows with how many streams × how much time, not with how clever the filter is.

Make the stream selector narrow, then filter

{namespace="shop", app="checkout"} |= "payment" != "healthz" | json | status >= 500

Order of operations that keeps queries cheap:

1. Label selector — as specific as possible.

2. Line filters (|=, !=, |~) — fast substring/regex on raw lines.

3. Parser (| json, | logfmt, | pattern, | regexp) — only on lines that survived.

4. Label filters on parsed fields (| status >= 500, | duration > 1s).

5. Formatting (| line_format).

Metric queries from logs

sum by (app) (rate({namespace="shop"} |= "level=error" [5m]))                 # errors per second
quantile_over_time(0.95, {app="checkout"} | json | unwrap duration_ms [5m]) by (route)  # p95 from a field
topk(5, sum by (path) (count_over_time({app="nginx"} | pattern "<_> \"<method> <path> <_>\" <code> <_>" | code="404" [1h])))

Labels: what to make a label

LabelNot a label
namespace, app, env, cluster, level (few values)trace_id, user_id, path with IDs, status_code per line

High-cardinality values create many tiny streams, which bloats the index and slows every query. Keep them in the line (or as structured metadata) and filter after selection. Check the cost of a query with the query statistics in Grafana Explore (bytes processed).

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Common mistakes

  • High-cardinality labels in Loki.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
logql queries in lokilogql loki queryloki label selector
Confirmation

Confirm action

Continue?