logql
Skill2 starsChanged 4 months agoMITView on GitHub
You MUST consult this skill when writing or debugging LogQL queries for Grafana Loki. Also trigger when building Grafana dashboard panels backed by Loki, creating log-based alerting rules, diagnosing empty results or parser errors, extracting metrics from logs with rate/count_over_time/unwrap, or correlating logs across multiple services. NOT for Loki deployment or configuration (see homelab-monitoring), Prometheus metrics (see promql), or PromQL dashboards.
In this repository67 other files it gives its agents.
- AGENTS.mdAGENTS.md
- agent-architectureSkill
- agent-evaluationSkill
- agent-memorySkill
- agent-post-trainingSkill
- agent-self-evolutionSkill
- agent-tool-designSkill
- api-designSkill
- application-architectureSkill
- brainstormSkill
- code-reviewerSkill
- coding-agent-designSkill
- concurrency-designSkill
- context-engineeringSkill
- dockerSkill
- game-audioSkill
- game-designSkill
- game-narrativeSkill
- game-patternsSkill
- game-performanceSkill
- game-renderingSkill
- game-visualsSkill
- git-commitSkill
- git-prSkill
- godot-shaderSkill
- godotSkill
- gpu-rendering-architectureSkill
- grafanaSkill
- helmSkill
- homelab-monitoringSkill
- k3sSkill
- k8s-networkingSkill
- k8s-operationsSkill
- k8s-storageSkill
- k8s-workloadsSkill
- knowledge-baseSkill
- level-designSkill
- llm-inference-servingSkill
- loggingSkill
- love2d-fennelSkill
- love2dSkill
- ml-platform-architectureSkill
- ml-post-trainingSkill
- multi-agent-collaborationSkill
- nix-dendriticSkill
- nix-packagingSkill
- nixSkill
- odin-designSkill
- odin-gamedevSkill
- orchestratorSkill
- physical-ai-systemsSkill
- plannerSkill
- prd-to-storiesSkill
- prd-writingSkill
- promqlSkill
- pr-reviewerSkill
- python-designSkill
- rag-designSkill
- ray-data-pipelinesSkill
- ray-kubernetes-infrastructureSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 2 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 31
Always include at least one exact-match label for performance.
- Very specific: line 141
Use unwrap duration_seconds(label) or unwrap bytes(label) for automatic unit conversion.
- Distinctive: line 232
Use PromQL for metrics from Prometheus exporters.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
LogQL Reference
LogQL is Grafana Loki's query language for selecting, filtering, parsing, and aggregating log streams. Two query types: log queries (return log lines) and metric queries (return numeric values). Syntax is inspired by PromQL.
Query Structure
{stream selector} | pipeline stage | pipeline stage | ...The stream selector is mandatory. Pipeline stages are optional and execute left-to-right.
Stream Selectors
Narrow as much as possible — this is the primary index lookup.
| Operator | Meaning |
= | Exact match |
!= | Not equal |
=~ | Regex match (RE2, fully anchored) |
!~ | Regex not match |
Always include at least one exact-match label for performance.
{container="sonarr"}
{compose_service="radarr", host="homelab"}
{container=~"sonarr|radarr|prowlarr"}Pipeline Stages
1. Line Filters — place BEFORE parsers
Distributed grep — cheapest filter. Run these first to reduce data before parsing.
| Operator | Meaning |
|= | Contains string |
!= | Does not contain |
|~ | Regex match (substring, NOT anchored) |
!~ | Regex not match |
Note:
|~and!~are not fully anchored — they match substrings. Only stream selector=~/!~are fully anchored (must match the entire label value).container=~"sonarr"matches onlysonarr; usecontainer=~"sonarr.*"for prefix.
{container="sonarr"} |= "error"
{container="plex"} != "healthcheck"
{container="adguard"} |~ "(?i)filtered" # case-insensitive substring match
{container="sonarr"} |= "error" != "timeout" # chains are ANDBacktick quoting avoids double-escaping: |~ `status=\d{3}`
2. Parsers — extract labels from log content
Choose by speed (fastest first):
| Parser | Syntax | Best For |
pattern | | pattern \<ip> - <> "<method> <path> <>" <status>`` | Fixed-format logs (fastest) |
logfmt | | logfmt | key=value logs |
json | | json or | json field="path" | JSON logs |
regexp | | regexp \(?P<name>regex)`` | Complex formats (slowest) |
Extract only needed fields — | json status, duration not | json.
Parser failure: Lines that fail to parse produce
__error__labels and are excluded from downstream label filters. If results are unexpectedly empty after a parser, check| __error__ != ""to see failing lines. Common cause: mixed log formats (startup banners mixed with JSON).
# Sonarr JSON logs — extract only what you need
{container="sonarr"} | json level, message
# Home Assistant logfmt
{container="homeassistant"} | logfmt domain, message
# Nginx access log with pattern
{container="nginx"} | pattern `<ip> - <_> "<method> <path> <_>" <status> <_>`
# Tautulli with regexp fallback
{container="tautulli"} | regexp `(?P<user>\w+) played (?P<title>.+)`3. Label Filters — after parsing
Typed comparisons on extracted labels:
{container="sonarr"} | json | level = "error"
{container="nginx"} | pattern `... <status> <_>` | status >= 500
{container="homeassistant"} | logfmt | duration > 10s
{container="plex"} | json | bytes > 5MBSupports: string (=, !=, =~), numeric (>, >=, <, <=), duration (> 10s), bytes (> 5MB), IP (= ip("192.168.0.0/24")).
4. Format Expressions
{container="sonarr"} | json | line_format "{{.level}} {{.message}}"
{container="nginx"} | json | label_format method=request_methodMetric Queries
Range Aggregations (no unwrap)
rate({container="sonarr"} |= "error" [5m]) # entries/second
count_over_time({container="adguard"} |= "filtered" [5m]) # total entries
bytes_rate({container="plex"} [5m]) # bytes/second
absent_over_time({container="sonarr"} [5m]) # 1 if no entries (alerting)Unwrapped Range Aggregations
Extract a numeric label, then aggregate over time:
# Average Plex transcode speed
avg_over_time(
{container="plex"} | logfmt | unwrap transcode_speed [5m]
)
# P99 Sonarr API response time
quantile_over_time(0.99,
{container="sonarr"} | json | unwrap response_time [5m]
)Functions: sum_over_time, avg_over_time, min_over_time, max_over_time, quantile_over_time(φ, ...), rate_counter, stddev_over_time.
Use unwrap duration_seconds(label) or unwrap bytes(label) for automatic unit conversion.
Aggregation Operators
Same as PromQL: sum, avg, min, max, count, topk, bottomk. Group with by() or without().
# AdGuard blocked DNS queries per minute
# AdGuard Home logs blocked queries with "filtered" in the line (text) or
# Reason field containing "Filtered*" (JSON). Check your log format first.
sum by (client) (
rate({container="adguard"} |= "filtered" [1m])
)
# Top 5 containers by error rate
topk(5,
sum by (container) (rate({host="homelab"} |= "error" [5m]))
)Cross-Service Correlation
Off-the-shelf containers (Sonarr, Radarr, Prowlarr, qBittorrent) can't inject trace IDs into their logs — there's no OpenTelemetry instrumentation. The homelab substitute for distributed tracing is correlating by shared domain identifiers that naturally appear across services: TMDB IDs, TVDB IDs, download hashes, NZB IDs. This is the homelab equivalent of a distributed trace query.
# All activity around a specific TMDB ID across *arr services
{container=~"sonarr|radarr|prowlarr"} |= "tmdbId=12345"
# Correlate by download hash across Sonarr and download client
{container=~"sonarr|qbittorrent"} |= "abc123hash"
# Find all Radarr + Prowlarr activity for a movie title
{container=~"radarr|prowlarr"} |~ "(?i)inception"
# Track a specific download from indexer search to completion
{container=~"prowlarr|sonarr|qbittorrent"} |= "NZB-ID-or-hash-here"Log-Based Alerting
groups:
- name: homelab_alerts
rules:
- alert: SonarrErrors
expr: |
sum(rate({container="sonarr"} |= "error" [5m])) > 0.1
for: 5m
labels:
severity: warning
annotations:
summary: "Sonarr error rate elevated"
- alert: AdGuardDown
expr: absent_over_time({container="adguard"}[5m])
for: 2m
labels:
severity: criticalOptimization
| Technique | Impact |
| Narrow stream selector with exact-match labels | High |
| Line filter before parser | High |
| Recording rules for dashboard panels | High |
Extract only needed fields (| json status) | Medium |
| Shorter time ranges | Medium |
pattern / logfmt faster than json; regexp slowest | Medium |
Avoid by(high-cardinality-label) (IPs, user IDs, request IDs) — use topk or filter to specific values | High |
Troubleshooting
| Problem | Cause & Fix |
| Empty results | Stream selector matches nothing — test {container="x"} alone first; check exact label name/value in Loki |
__error__ labels appear | Parser failed on some lines. Debug: | __error__ != "" to see failing lines. Drop them: | __error__ = "". For JSON: add |= "{" before | json. For pattern: verify pattern matches actual log format. |
| Query timeout | Causes: regexp parser on high-volume stream, |~ regex filter without a preceding |= string filter, long time range with unwrap aggregations. Fixes: add exact-match labels, place |= before |~, reduce time range. Recording rules require Loki ruler (see homelab-monitoring skill). |
LogQL vs PromQL
| Feature | PromQL | LogQL |
| Data source | Metrics (time series) | Logs (text streams) |
| Selectors | metric{label="value"} | {label="value"} (no metric name) |
| Parsing | N/A (structured) | json, logfmt, pattern, regexp |
| Line filtering | N/A | |=, !=, |~, !~ |
| Unwrap | N/A | Extract numeric values from logs |
| Aggregations | Same operators | Same operators |
Use PromQL for metrics from Prometheus exporters. Use LogQL when the data lives in log lines.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

