TExcelTAD

LogQL Metric Queries

Wrap a log query in a function over a time window and it becomes a metric query: numbers instead of lines, with the same aggregation operators as PromQL. That lets you graph and alert on things only logs know about, such as a specific error message, without adding a metric to the code.

Function Over each stream's lines in the window
count_over_time({…}[5m]) number of lines
rate({…}[5m]) lines per second
bytes_over_time, bytes_rate log volume (cost!)
absent_over_time({…}[15m]) 1 if there were no lines at all: "the app stopped logging"
sum_over_time, avg_over_time, max_over_time, quantile_over_time(0.99, …) on a number unwrapped from each line: `

Then aggregate with sum by (…), topk, avg, … exactly like PromQL. Labels produced by a parser can be used in by (sum by (status) (…| json …)), which is powerful and dangerous: grouping by a high-cardinality parsed field produces huge results.

On the linkly logs

Same Loki and the same two minutes of logs as in LogQL: Filtering & Parsing. Metric queries are evaluated at a fixed time with logcli instant-query --now, or over a range with logcli query --step; jq turns Loki's JSON answer into one line per series:

bash · try it yourself
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
streams = {}
for s in range(120):
    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
iq() { echo "> $1"; logcli instant-query --quiet --now=2026-01-01T10:02:00Z "$1" |
       jq -r '.[] | "\(.metric | tostring) \(.value[1])"' | sort; }

iq 'sum by (pod) (count_over_time({app="linkly"}[2m]))'
iq 'sum by (level) (count_over_time({app="linkly"} | json [2m]))'
iq 'sum(count_over_time({app="linkly"} |= "statement timeout" [2m])) / sum(count_over_time({app="linkly"}[2m]))'
iq 'sum by (route) (rate({app="linkly"} | json | status >= 500 [2m]))'
iq 'quantile_over_time(0.99, {app="linkly"} | json | route = "/{code}" | unwrap duration_ms [2m]) by (route)'
iq 'topk(1, sum by (msg) (count_over_time({app="linkly"} | json | level != "INFO" [2m])))'
echo "> errors per 30 s (range query)"
logcli query --quiet --from=2026-01-01T10:00:00Z --to=2026-01-01T10:02:00Z --step=30s \
  'sum(count_over_time({app="linkly"} |= "ERROR" [30s]))' | jq -r '.[].values[] | "\(.[0] | todate) \(.[1])"'
> sum by (pod) (count_over_time({app="linkly"}[2m]))
{"pod":"linkly-0"} 59
{"pod":"linkly-1"} 60
> sum by (level) (count_over_time({app="linkly"} | json [2m]))
{"level":"ERROR"} 7
{"level":"INFO"} 108
{"level":"WARN"} 4
> sum(count_over_time({app="linkly"} |= "statement timeout" [2m])) / sum(count_over_time({app="linkly"}[2m]))
{} 0.058823529411764705
> sum by (route) (rate({app="linkly"} | json | status >= 500 [2m]))
{"route":"/links"} 0.058333333333333334
> quantile_over_time(0.99, {app="linkly"} | json | route = "/{code}" | unwrap duration_ms [2m]) by (route)
{"route":"/{code}"} 494.3900000000001
> topk(1, sum by (msg) (count_over_time({app="linkly"} | json | level != "INFO" [2m])))
{"msg":"create link failed"} 7
> errors per 30 s (range query)
2026-01-01T10:00:30Z 2
2026-01-01T10:01:30Z 2
2026-01-01T10:02:00Z 3

Reading it:

  • The two pods logged one line per second between them, but the counts are 59 and 60: like PromQL, the window (10:00:00, 10:02:00] excludes its start, so linkly-0's first line at exactly 10:00:00 is not counted.
  • sum by (level) used the parsed level; 7 of 119 lines are errors, 5.9%, the same as the "statement timeout" ratio on the next line.
  • rate(… [2m]) is per second, like PromQL: 7 errors / 120 s ≈ 0.058/s.
  • unwrap duration_ms turns the field into the sample value, so quantile_over_time gives a p99 from logs (with by (route) written after the function, a LogQL quirk for unwrapped range aggregations). It's exact over the lines, but costly: prefer histograms in code for latency, and use this when the logs are all you have (a proxy, a third-party app).
  • topk(1, …) finds the most frequent non-INFO message.
  • The range query bins errors into 30-second steps, exactly what a Grafana bar chart of errors over time would show. Steps without any error (10:00:00, 10:01:00) are simply missing, not 0; add or vector(0) if a panel should show zeros.

Alerting and recording from logs

Loki has a ruler that evaluates LogQL rules in Prometheus's rule-file format and sends alerts to Alertmanager:

yaml
# loki rules file (sample), e.g. /loki/rules/fake/linkly.yaml for the single tenant "fake"
groups:
  - name: linkly-logs
    rules:
      - alert: LinklyStatementTimeouts
        expr: sum(count_over_time({app="linkly", env="prod"} |= "statement timeout" [5m])) > 20
        for: 5m
        labels: {severity: ticket, service: linkly}
        annotations:
          summary: "{{ $value }} PostgreSQL statement timeouts in 5 minutes"
      - alert: LinklyStoppedLogging
        expr: absent_over_time({app="linkly", env="prod"}[15m])
        labels: {severity: ticket}
      - record: app:log_lines:rate1m             # written to Prometheus via remote write
        expr: sum by (app) (rate({env="prod"}[1m]))
yaml
# loki.yaml additions
ruler:
  storage: {type: local, local: {directory: /loki/rules}}
  rule_path: /tmp/loki-rules-scratch
  alertmanager_url: http://alertmanager:9093
  enable_api: true
  remote_write:
    enabled: true
    client: {url: http://prometheus:9090/api/v1/write}

Recording rules are the efficient way to keep long-term log metrics (lines per app per minute, errors by message) without scanning months of logs for every dashboard load.

Test yourself

What does count_over_time({app="linkly"} |= "panic" [5m]) return?

  1. The panic lines
  2. The number of lines containing "panic" per stream in the last 5 minutes
  3. A boolean
  4. The bytes logged

What does | unwrap duration_ms do?

  1. Removes the field
  2. Uses the field's numeric value as the sample value for *_over_time functions
  3. Formats the line
  4. Converts ms to seconds automatically

Which LogQL expression alerts when an app stops logging entirely?

  1. count_over_time({app="x"}[15m]) == 0
  2. absent_over_time({app="x"}[15m])
  3. rate({app="x"}[15m]) < 0
  4. {app="x"} != ""