123DevOps··5 min read

Querying logs with Loki and LogQL: from simple filters to metrics from logs

Label selectors, line filters, json and logfmt parsers, field filters, formatting, metrics with count_over_time and unwrap, trace correlation, logcli, and performance tips.

Observability

During an incident, knowing how to query logs quickly is the difference between finding the cause in two minutes or in half an hour. In this guide, we use Loki and its query language, LogQL, in Grafana’s Explore — but the same concepts (select, filter, parse, aggregate) apply to any log tool.

If you’re not yet familiar with Loki’s role in the stack, start with the LGTM stack explainer.

The anatomy of a LogQL query

{namespace="checkout", app="api"} |= "payment" | json | status >= 500 | line_format "{{.method}} {{.path}} {{.status}}"

Reading from left to right:

  1. Stream selector {...}: chooses which logs to read, using indexed labels. It’s required.
  2. Line filter |= "payment": keeps only the lines that contain the text.
  3. Parser | json: turns the JSON fields into temporary labels.
  4. Field filter | status >= 500: filters on the extracted values.
  5. Formatting | line_format: changes how the line is displayed.

1. Selectors: always start narrow

{namespace="checkout"}                         # all logs in the namespace
{namespace="checkout", app="api"}              # just the API
{namespace=~"checkout|payments"}               # regex on labels
{namespace="checkout", app!="worker"}          # exclusion

The selector determines how much data Loki has to read. The more specific it is, the faster the query. Use the labels your collector already adds (namespace, app, pod, container, cluster).

2. Line filters: Loki’s grep

{app="api"} |= "error"                 # contains
{app="api"} != "healthz"               # does not contain
{app="api"} |~ "timeout|refused"       # regex
{app="api"} !~ "(?i)debug"             # negated regex, case-insensitive

Line filters are very fast and should come before parsers: discarding lines early saves processing.

3. Parsers: turning text into fields

For JSON logs:

{app="api"} | json

For logs in key=value format (logfmt):

{app="api"} | logfmt

For unstructured formats, the pattern parser extracts fields by position:

{app="nginx"} | pattern `<ip> - - [<_>] "<method> <path> <_>" <status> <bytes>`

After the parser, each field becomes a temporary label that can be filtered and used in aggregations.

4. Filtering by fields

{app="api"} | json | status >= 500
{app="api"} | json | duration_ms > 1000 and method = "POST"
{app="api"} | json | user_plan = "enterprise"

This is where instrumentation with business context pays off: with fields like plan, payment method, and version, the question “who is being affected?” becomes a filter.

5. Formatting the output

{app="api"} | json | status >= 500
  | line_format "{{.method}} {{.path}} → {{.status}} ({{.duration_ms}} ms) trace={{.trace_id}}"

A formatted line is much easier to read on an incident screen than a 40-field JSON blob.

6. Metrics from logs

LogQL can also produce time series from logs — great for graphs and alerts.

Errors per minute, by application:

sum by (app) (count_over_time({namespace="checkout"} |= "error" [1m]))

Rate of 5xx responses by route:

sum by (path) (rate({app="api"} | json | status >= 500 [5m]))

p95 latency extracted from a numeric log field, using unwrap:

quantile_over_time(0.95,
  {app="api"} | json | unwrap duration_ms [5m]
) by (path)

These queries can become panels in your dashboards and alert rules in Grafana or in Loki’s ruler. If one of these queries is used all the time, consider generating the metric directly in the application or in the telemetry pipeline: it’s cheaper than reprocessing logs.

7. Correlating with traces

If your logs carry the trace_id (as we showed in correlating signals), configure a derived field in the Loki data source:

  • Name: TraceID
  • Regex: "trace_id":"(\w+)" (or whatever format your logs use)
  • Internal link: Tempo data source, query ${__value.raw}

From then on, every log line with a trace_id gets a button that opens the full trace of the request.

Labels: the mistake that makes Loki slow and expensive

In Loki, labels define the streams. Each unique combination of labels is a separate stream. That’s why:

  • Good labels: namespace, app, cluster, level — few possible values.
  • Terrible labels: trace_id, user_id, request_id, path with IDs — millions of tiny streams, slow ingestion, and worse queries.

High-cardinality fields should stay in the line content (filtered with parsers) or go into structured metadata, which travels with the line without entering the index. It’s the same reasoning as cardinality in metrics.

Querying from the terminal: logcli

export LOKI_ADDR=https://loki.example.com
logcli query '{app="checkout"} |= "error"' --since=1h --limit=50
logcli query '{app="checkout"} | json | status >= 500' --since=30m --output=jsonl

Useful in scripts, on servers without access to Grafana, and for exporting results.

What if your logs live somewhere else?

The concepts carry over. In CloudWatch Logs Insights, for example:

fields @timestamp, @message
| filter @message like /ERROR/
| stats count(*) by bin(5m)

In Elasticsearch/OpenSearch, the equivalent is done with KQL or DSL queries. Select, filter early, parse, and aggregate are still the four steps.

Performance tips

  1. Short time range: start with 15 minutes or 1 hour and widen it if needed.
  2. Specific selector: namespace and app, at a minimum.
  3. Line filter before the parser: |= "error" | json is much faster than | json | level="error".
  4. Avoid regex when plain text will do.
  5. Line limit in Explore for exploratory queries.

Checklist

  • Structured logs (JSON or logfmt) in your applications
  • Low-cardinality labels defined in the collector
  • trace_id on every line and a derived field pointing to Tempo
  • Saved queries for the most common incidents
  • Log-based metrics in your key dashboards and alerts
  • Team trained on the four steps: select, filter, parse, aggregate

Logs aren’t for storing everything. They’re for answering the right question fast — and LogQL is how you ask that question.

Get updates on new posts and stay in the loop!