
Logql Generator
- 378 installs
- 286 repo stars
- Updated July 26, 2026
- akin-ozer/cc-devops-skills
Author LogQL queries to search, filter, aggregate, and alert on Grafana Loki log streams during incident triage or dashboard design.
About
Generates Grafana Loki LogQL queries for log line filtering, JSON parsing, rate and count aggregations, and label-based drilldowns used in dashboards, alerts, and on-call investigations.
- Label selector query construction
- Line filter and parser patterns
- Metric and range aggregation examples
- Incident-friendly query templates
Logql Generator by the numbers
- 378 all-time installs (skills.sh)
- Ranked #310 of 1,435 DevOps & CI/CD skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/akin-ozer/cc-devops-skills --skill logql-generatorAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 378 |
|---|---|
| repo stars | ★ 286 |
| Last updated | July 26, 2026 |
| Repository | akin-ozer/cc-devops-skills ↗ |
What it does
Author LogQL queries to search, filter, aggregate, and alert on Grafana Loki log streams during incident triage or dashboard design.
Files
LogQL Query Generator
Overview
Interactive workflow for generating production-ready LogQL queries. LogQL is Grafana Loki's query language with indexed label selection, line filtering, parsing, and metric aggregation.
Trigger Hints
- "Write a LogQL query for error rate by service."
- "Help me build a Loki alert query."
- "Convert this troubleshooting requirement into LogQL."
- "I need step-by-step LogQL query construction."
Use this skill for query generation, dashboard queries, alerting expressions, and troubleshooting with Loki logs.
Execution Flow (Deterministic)
Always run stages in order. Do not skip required stages.
Stage 1 (Required): Capture Intent
Use AskUserQuestion to collect goal and use case.
Template:
- "What is your primary goal: debugging, alerting, dashboard metric, or investigation?"
- "Do you need a log query (raw lines) or a metric query (numeric output)?"
- "What time window should this cover (example: last 15m, 1h, 24h)?"
Fallback if AskUserQuestion is unavailable:
- Ask the same questions in plain text and continue.
Stage 2 (Required): Capture Log Source Details
Collect: 1. Labels for stream selectors (job, namespace, app, service_name, cluster) 2. Log format (JSON, logfmt, plain text, mixed) 3. Known fields to filter/aggregate (status, level, duration, path, trace_id)
Ambiguity and partial-answer handling: 1. If a required field is missing, ask one focused follow-up question. 2. If still missing, proceed with explicit assumptions. 3. Prefix assumptions with Assumptions: in the output so the user can correct them quickly.
Stage 3 (Required): Discover Loki and Grafana Versions
Collect or infer:
- Loki version (example:
2.9.x,3.0+, unknown) - Grafana version (example:
10.x,11.x, unknown) - Deployment context (self-hosted Loki, Grafana Cloud, unknown)
Version compatibility policy: 1. If versions are known, use the newest compatible syntax only. 2. If versions are unknown, use compatibility-first syntax and avoid 3.x-only features by default. 3. For unknown versions, provide an optional "3.x optimized variant" separately.
Avoid by default when version is unknown:
- Pattern match operators
|>and!> approx_topk- Structured metadata specific behavior (
detected_level, accelerated metadata filtering assumptions)
Stage 4 (Required): Plan Confirmation and Output Mode
Present a plain-English plan, then ask the user to choose output mode.
Plan template:
LogQL Query Plan
Goal: <goal>
Query type: <log or metric>
Streams: <selector>
Filters/parsing: <filters + parser>
Aggregation window: <function and [range]>
Compatibility mode: <version-aware or compatibility-first>Mode selection template:
- "Do you want
final query only(default) orincremental build(step-by-step)?"
If user does not choose, default to final query only.
Stage 5 (Conditional, Blocking): Reference Checkpoint for Complex Queries
Complex query triggers:
- Nested aggregations (
topk(sum by(...)), multiplesum by, percentiles) - Performance-sensitive queries (high volume streams, long ranges)
- Alerting expressions
- Template functions (
line_format,label_format) - Regex-heavy extraction, IP matching, pattern parsing
- Loki 3.x feature usage
Blocking checkpoint rule: 1. Read relevant files before generation using explicit file-open/read actions. 2. Minimum file set:
examples/common_queries.logqlfor syntax and query patternsreferences/best_practices.mdfor performance and alerting guidance
3. Do not generate the final query until this checkpoint is complete.
Fallback when file-read tools are unavailable: 1. State that reference files could not be read in this environment. 2. Generate a conservative query (compatibility-first, simpler operators). 3. Mark result as Unverified against local references.
Stage 6 (Conditional): External Docs Lookup Policy (Context7 Before WebSearch)
Use external lookup only for version-specific behavior, unclear syntax, or advanced features not covered in local references.
Decision order: 1. Context7 first:
mcp__context7__resolve-library-idwithlibraryName="grafana loki"mcp__context7__query-docsfor the exact topic
2. WebSearch second (fallback only) when:
- Context7 is unavailable
- Context7 does not provide required version-specific detail
- You need latest release/deprecation confirmation
WebSearch fallback constraints:
- Prefer official Grafana/Loki docs and release notes.
- Note which statement came from fallback search.
Stage 7 (Required): Generate Query
Stage 7A (Default): Final Query Only
Return one production-ready query plus short explanation.
Stage 7B (Optional): Incremental Build Mode
Use this when requested or when debugging complex pipelines.
Step-by-step template: 1. Stream selector 2. Line filter 3. Parser 4. Parsed-field filter 5. Aggregation/window
Stage 8 (Required): Deliver Usage and Checks
Always include: 1. Final query or incremental sequence 2. How to run it (Grafana Explore/panel or logcli) 3. Tunables (labels, thresholds, range) 4. Any assumptions and compatibility notes
AskUserQuestion Templates
Intake Template
- "What system/service should this query target?"
- "Which labels are reliable for stream selection?"
- "What defines a match (error text, status code, latency threshold, user path)?"
- "Should output be raw logs or a metric for alert/dashboard?"
Version Template
- "What Loki version are you running?"
- "What Grafana version are you using?"
- "If unknown, should I generate a compatibility-first query and add an optional 3.x variant?"
Ambiguity Follow-up Template
- "I am missing
<field>. Should I assume<default>so I can continue?"
Core Patterns
Stream Selection and Filtering
{job="app"} |= "error" |= "timeout"
{job="app"} |~ "error|fatal|critical"
{job="app"} != "debug"Parsing
{app="api"} | json | level="error" | status_code >= 500
{app="api"} | logfmt | caller="database.go"
{job="nginx"} | pattern "<ip> - - [<_>] \"<method> <path>\" <status> <size>"Metric Aggregation
rate({job="app"} | json | level="error" [5m])
sum by (app) (count_over_time({namespace="prod"} | json [5m]))
sum(rate({app="api"} | json | level="error" [5m])) / sum(rate({app="api"}[5m])) * 100
quantile_over_time(0.95, {app="api"} | json | unwrap duration [5m])
topk(10, sum by (error_type) (count_over_time({job="app"} | json | level="error" [1h])))Formatting and IP Matching
{job="app"} | json | line_format "{{.level}}: {{.message}}"
{job="app"} | json | label_format env=`{{.environment}}`
{job="nginx"} | logfmt | remote_addr = ip("192.168.4.0/24")Query Construction Rules
1. Use specific stream selectors (indexed labels first). 2. Prefer filter order: line filter -> parse -> parsed-field filter. 3. Prefer parser cost order: pattern > logfmt > json > regexp. 4. For unknown Loki version, stay on compatibility-first syntax. 5. For complex/critical queries, complete Stage 5 checkpoint before final output.
Advanced Techniques
Multiple Parsers
{app="api"} | json | regexp "user_(?P<user_id>\\d+)"Unwrap for Numeric Metrics
sum(sum_over_time({app="api"} | json | unwrap duration [5m]))Pattern Match Operators (Loki 3.0+, 10x faster than regex)
{service_name=`app`} |> "<_> level=debug <_>"Logical Operators
{app="api"} | json | (status_code >= 400 and status_code < 500) or level="error"Offset Modifier
sum(rate({app="api"} | json | level="error" [5m])) - sum(rate({app="api"} | json | level="error" [5m] offset 1d))Label Operations
{app="api"} | json | keep namespace, pod, level
{app="api"} | json | drop pod, instanceNote: LogQL has nodedupordistinctoperators. Use metric aggregations likesum by (field)for programmatic deduplication.
Loki 3.x Key Features
Structured Metadata
High-cardinality data without indexing (trace_id, user_id, request_id):
# Filter AFTER stream selector, NOT in it
{app="api"} | trace_id="abc123" | json | level="error"Query Acceleration (Bloom Filters)
Place structured metadata filters BEFORE parsers:
# ACCELERATED
{cluster="prod"} | detected_level="error" | logfmt | json
# NOT ACCELERATED
{cluster="prod"} | logfmt | json | detected_level="error"approx_topk (Probabilistic)
approx_topk(10, sum by (endpoint) (rate({app="api"}[5m])))vector() for Alerting
sum(count_over_time({app="api"} | json | level="error" [5m])) or vector(0)Automatic Labels
- service_name: Auto-populated from container name
- detected_level: Auto-detected when
discover_log_levels: true(stored as structured metadata)
Function Reference
Log Range Aggregations
| Function | Description |
|---|---|
rate(log-range) | Entries per second |
count_over_time(log-range) | Count entries |
bytes_rate(log-range) | Bytes per second |
bytes_over_time(log-range) | Total bytes in time range |
absent_over_time(log-range) | Returns 1 if no logs |
Rule:
- Use
bytes_over_time(<log-range>)for raw log-byte volume. - Use
| unwrap bytes(field)with unwrapped range aggregations for numeric byte fields extracted from log content.
Unwrapped Range Aggregations
| Function | Description |
|---|---|
sum_over_time, avg_over_time, max_over_time, min_over_time | Aggregate numeric values |
quantile_over_time(φ, range) | φ-quantile (0 ≤ φ ≤ 1) |
first_over_time, last_over_time | First/last value in interval |
stddev_over_time | Population standard deviation of unwrapped values |
stdvar_over_time | Population variance of unwrapped values |
rate_counter | Per-second rate treating values as a monotonically increasing counter |
Aggregation Operators
sum, avg, min, max, count, stddev, topk, bottomk, approx_topk, sort, sort_desc
With grouping: sum by (label1, label2) or sum without (label1)
Conversion Functions
| Function | Description |
|---|---|
duration_seconds(label) | Convert duration string |
bytes(label) | Convert byte string (KB, MB) |
label_replace()
label_replace(rate({job="api"} |= "err" [1m]), "foo", "$1", "service", "(.*):.*")Parser Reference
logfmt
| logfmt [--strict] [--keep-empty]--strict: Error on malformed entries--keep-empty: Keep standalone keys
JSON
| json # All fields
| json method="request.method", status="response.status" # Specific fields
| json servers[0], headers="request.headers[\"User-Agent\"]" # Nested/arraypattern
| pattern "<ip> - - [<timestamp>] \"<method> <path> <_>\" <status> <size>"Named placeholders become extracted labels; <_> discards a field.
regexp
| regexp "(?P<level>\\w+): (?P<message>.+)"Uses named capture groups (?P<name>). Slower than pattern/logfmt/json.
decolorize
| decolorizeStrips ANSI color escape codes. Apply before parsing when logs come from terminal output.
unpack
| unpackUnpacks log entries that were packed by Promtail's pack pipeline stage. Restores the original log line and any embedded labels.
Template Functions
Common functions for line_format and label_format:
String: trim, upper, lower, replace, trunc, substr, printf, contains, hasPrefix Math: add, sub, mul, div, addf, subf, floor, ceil, round Date: date, now, unixEpoch, toDate, duration_seconds Regex: regexReplaceAll, count Other: fromJson, default, int, float64, __line__, __timestamp__
See examples/common_queries.logql for detailed usage.
Alerting Rules
# Alert when error rate exceeds 5%
(sum(rate({app="api"} | json | level="error" [5m])) / sum(rate({app="api"}[5m]))) > 0.05
# With vector() to avoid "no data"
sum(rate({app="api"} | json | level="error" [5m])) or vector(0) > 10Error Handling
| Issue | Solution |
|---|---|
| No results | Check labels exist, verify time range, test stream selector alone |
| Query slow | Use specific selectors, filter before parsing, reduce time range |
| Parse errors | Verify log format matches parser, test JSON validity |
| High cardinality | Use line filters not label filters for unique values, aggregate |
Documentation Lookup
Use Stage 6 policy. Trigger external docs for:
| Trigger | Topic to Search | Tool to Use |
|---|---|---|
| User mentions Loki 3.x features | structured metadata, bloom filters, detected_level | Context7 first |
approx_topk function needed | approx_topk probabilistic | Context7 first |
| Pattern match operators (`\ | >, !>`) | pattern match operator |
vector() function for alerting | vector function alerting | Context7 first |
| Recording rules configuration | recording rules loki | Context7 first |
| Unclear syntax or edge cases | Specific function/operator | Context7 first |
| Version-specific behavior questions | Version + feature | WebSearch fallback |
| Grafana Alloy integration | grafana alloy loki | WebSearch fallback |
Resources
examples/common_queries.logql: Query patterns, template function examplesreferences/best_practices.md: Optimization, anti-patterns, alerting guidance
Example Flows
Example A: Final Query Only (Default)
1. User asks for 5xx rate by service over 15m. 2. Capture labels and format (json). 3. Confirm version and mode (final query only). 4. Generate one query:
sum by (service) (rate({namespace="prod", app="api"} | json | status_code >= 500 [15m]))Example B: Incremental Build (Optional)
1. User asks to debug login failures and requests step-by-step mode. 2. Provide staged build:
{app="auth"}
{app="auth"} |= "login failed"
{app="auth"} |= "login failed" | json
sum(count_over_time({app="auth"} |= "login failed" | json [5m]))3. Explain where to stop if any step returns zero results.
Done Criteria
Mark task done only when all checks pass: 1. Required stages (1, 2, 3, 4, 7, 8) were completed. 2. Stage 5 checkpoint was completed for any complex query. 3. Stage 6 lookup order followed Context7 before WebSearch when external docs were needed. 4. Output mode was explicitly selected or defaulted (final query only). 5. Loki/Grafana compatibility assumptions were stated when versions were unknown. 6. Final output includes query text, usage note, tunables, and assumptions.
Version Notes
- Loki 3.0+: Bloom filters, structured metadata, pattern match operators (
|>,!>) - Loki 3.3+:
approx_topkfunction - Loki 3.5+: Promtail deprecated (use Grafana Alloy)
- Loki 3.6+: Horizontally scalable compactor, Loki UI as Grafana plugin
Deprecations: Promtail (use Alloy), BoltDB store (use TSDB with v13 schema)
# Common LogQL Query Examples
# These queries demonstrate typical use cases for log analysis with Grafana Loki
## === BASIC LOG QUERIES ===
# Find all error logs
{job="app"} |= "error"
# Find logs containing "error" or "fatal"
{job="app"} |~ "error|fatal"
# Find errors NOT containing "timeout"
{job="app"} |= "error" != "timeout"
# Regex pattern matching
{job="nginx"} |~ "HTTP/[0-9.]+ (4|5)[0-9]{2}"
## === JSON LOG PARSING ===
# Parse JSON logs and filter by level
{app="api"} | json | level="error"
# Parse JSON and filter by multiple fields
{app="api"} | json | method="POST" | status_code >= 400
# Parse nested JSON fields
{app="api"} | json request.method="POST", response.status_code >= 500
# Extract and display specific JSON fields
{app="api"} | json | line_format "{{.level}}: {{.message}}"
## === LOGFMT PARSING ===
# Parse logfmt format
{app="app"} | logfmt
# Parse and filter logfmt logs
{app="app"} | logfmt | level="error" | caller="database.go"
## === LOGFMT PARSER FLAGS (Loki 3.x) ===
# Basic logfmt parsing
{app="api"} | logfmt
# Strict mode - fail on malformed key=value pairs (stops on error)
{app="api"} | logfmt --strict
# Keep standalone keys as labels with empty string value
{app="api"} | logfmt --keep-empty
# Combine flags for strict parsing with empty key retention
{app="api"} | logfmt --strict --keep-empty
# Strict mode with label extraction parameters
{app="api"} | logfmt --strict host, fwd_ip="fwd"
# Detect malformed log entries using strict mode
{app="api"} | logfmt --strict | __error__ != ""
# Production query - strict mode with error filtering
{app="api"} | logfmt --strict | __error__="" | level="error"
## === JSON PARSER WITH PARAMETER EXTRACTION ===
# Extract all fields (default behavior)
{app="api"} | json
# Extract specific fields by name (more efficient)
{app="api"} | json status, method, duration
# Extract with custom label names using expressions
{app="api"} | json first_server="servers[0]", ua="request.headers[\"User-Agent\"]"
# Extract arrays/objects as JSON strings
{app="api"} | json server_list="servers", headers="request.headers"
# Shorthand - label name equals field name
{app="api"} | json servers
# Extract nested request fields using dot notation
{app="api"} | json method="request.method", status="response.status_code"
# Extract nested fields with array access
{app="api"} | json first_item="items[0].name", last_item="items[-1].name"
# Combined with bracket notation for special characters
{app="api"} | json content_type="headers[\"Content-Type\"]"
# Combined with filtering on extracted fields
{app="api"} | json status="response.status" | status >= 400
# Extract only what you need for performance
{app="api"} | json level, message, trace_id | level="error"
## === PATTERN EXTRACTION ===
# Extract fields using pattern syntax
{job="nginx"} | pattern "<ip> - - [<timestamp>] \"<method> <path> <protocol>\" <status> <size>"
# Pattern extraction with filtering
{job="nginx"} | pattern "<ip> - - [<_>] \"<method> <_>\" <status> <_>" | status >= 400
# Pattern with wildcards
{service_name="distributor"} |> "<_> level=debug <_> msg=\"POST /push <_>\""
## === REGEX PARSING ===
# Extract fields with named capture groups
{app="app"} | regexp "(?P<level>\\w+): (?P<message>.+)"
# Extract IP addresses and HTTP codes
{job="nginx"} | regexp "(?P<ip>\\d+\\.\\d+\\.\\d+\\.\\d+) .* (?P<status>\\d{3})"
## === ERROR ANALYSIS ===
# Count errors over time
count_over_time({app="api"} | json | level="error" [5m])
# Error rate per second
sum(rate({app="api"} | json | level="error" [5m]))
# Error percentage
(
sum(rate({app="api"} | json | level="error" [5m]))
/
sum(rate({app="api"}[5m]))
) * 100
# Errors by type
sum by (error_type) (
count_over_time({app="api"} | json | level="error" [5m])
)
# Top 10 error messages
topk(10,
sum by (error_message) (
count_over_time({app="api"} | json | level="error" [1h])
)
)
## === PERFORMANCE MONITORING ===
# Find slow requests (>1 second)
{app="api"} | json | duration > 1
# Average response time
avg_over_time({app="api"} | json | unwrap duration [5m])
# 95th percentile latency
quantile_over_time(0.95, {app="api"} | json | unwrap duration [5m])
# 99th percentile latency
quantile_over_time(0.99, {app="api"} | json | unwrap duration [5m])
# Max response time in last 5 minutes
max_over_time({app="api"} | json | unwrap duration [5m])
# Requests by latency bucket
sum by (le) (
count_over_time({app="api"} | json | duration > 0 [5m])
)
## === TRAFFIC ANALYSIS ===
# Total log volume (logs per second)
sum(rate({namespace="production"}[5m]))
# Logs per second by application
sum by (app) (rate({namespace="production"}[5m]))
# Bytes per second
sum(bytes_rate({job="app"}[5m]))
# Request rate by endpoint
sum by (endpoint) (rate({app="api"} | json [5m]))
# HTTP status code distribution
sum by (status_code) (
count_over_time({app="api"} | json [5m])
)
# Requests per second by method
sum by (method) (rate({app="api"} | json [5m]))
## === SECURITY MONITORING ===
# Failed login attempts
{app="auth"} | json | event="login_failed"
# Failed logins by user
sum by (username) (
count_over_time({app="auth"} | json | event="login_failed" [1h])
)
# Top 10 users with failed logins
topk(10,
sum by (username) (
count_over_time({app="auth"} | json | event="login_failed" [1h])
)
)
# Suspicious activity (unauthorized access attempts)
{app="api"} | json | (status_code == 401 or status_code == 403)
# Access from external IPs (requires a parsed label that holds the IP, e.g. source_ip)
{app="api"} | json | source_ip != ip("10.0.0.0/8") | source_ip != ip("172.16.0.0/12") | source_ip != ip("192.168.0.0/16")
# SQL injection attempts
{app="api"} |~ "union.*select|select.*from.*where"
## === USER BEHAVIOR TRACKING ===
# Top 10 users by activity
topk(10,
sum by (user_id) (rate({app="api"}[5m]))
)
# User sessions by endpoint
sum by (user_id, endpoint) (
count_over_time({app="api"} | json [1h])
)
# User actions per minute
sum by (user_id, action) (
rate({app="api"} | json [1m])
)
## === APPLICATION DEBUGGING ===
# Logs from specific trace ID
{app="api"} | json | trace_id="abc123xyz"
# Logs for specific user session
{app="api"} | json | session_id="sess_12345"
# Debug logs with context
{app="api", level="debug"} | json | line_format "{{.timestamp}} [{{.trace_id}}] {{.message}}"
# Stack traces (multi-line logs)
{app="api"} |= "Exception" | json
# Database query errors
{app="api"} | json | component="database" | level="error"
## === LOG VOLUME AND RATES ===
# Total logs in last hour
sum(count_over_time({namespace="production"}[1h]))
# Peak log rate in last 24 hours
max_over_time(
sum(rate({namespace="production"}[5m]))[24h:5m]
)
# Average log rate by hour
avg_over_time(
sum(rate({namespace="production"}[5m]))[1h:5m]
)
# Logs by namespace
sum by (namespace) (rate({job="kubernetes-pods"}[5m]))
## === FILTERING AND TRANSFORMATION ===
# Remove ANSI color codes
{app="app"} | decolorize
# Keep only specific labels
{app="api"} | json | keep namespace, pod, level, message
# Drop noisy labels
{app="api"} | json | drop instance, pod
# Rename labels
{app="api"} | json | label_format env=`{{.environment}}`, svc=`{{.service}}`
# NOTE: LogQL does NOT have a native `dedup` operator
# Deduplication is a UI-level feature in Grafana's Explore panel
# For programmatic deduplication, use metric aggregations:
# sum by (message) (count_over_time({app="api"} | json [5m])) > 0
## === IP ADDRESS FILTERING ===
# The ip() function filters based on a label value containing an IP address
# It supports: single IPs, CIDR notation, and IP ranges
# Logs from specific IP (exact match)
{app="api"} | json | client_ip="192.168.1.100"
# Logs from IP range using CIDR notation (apply ip() to a specific label)
{job="nginx"} | logfmt | remote_addr = ip("192.168.1.0/24")
# Logs NOT from internal network (negate with !=)
{job="nginx"} | logfmt | remote_addr != ip("10.0.0.0/8")
# Logs from IP range (start-end format)
{job="nginx"} | logfmt | remote_addr = ip("192.168.4.5-192.168.4.20")
# Logs from multiple IP ranges (combine with or)
{job="nginx"} | logfmt | remote_addr = ip("192.168.0.0/16") or remote_addr = ip("10.0.0.0/8")
# Exclude specific IP within a range
{job="nginx"} | logfmt | remote_addr = ip("192.168.4.0/24") | remote_addr != ip("192.168.4.2")
# IPv6 address range filtering
{job="nginx"} | logfmt | remote_addr = ip("2001:db8::1-2001:db8::8")
# Line filter with IP (less precise, may have false positives)
{job="nginx"} |= ip("192.168.4.5/16")
## === TIME-BASED COMPARISONS ===
# Current error rate vs 1 hour ago
sum(rate({app="api"} | json | level="error" [5m]))
-
sum(rate({app="api"} | json | level="error" [5m] offset 1h))
# Current vs yesterday same time
sum(rate({app="api"}[5m]))
/
sum(rate({app="api"}[5m] offset 1d))
# Week-over-week comparison
sum(rate({app="api"} | json | level="error" [5m]))
/
sum(rate({app="api"} | json | level="error" [5m] offset 1w))
## === AGGREGATION EXAMPLES ===
# Sum of request durations
sum(sum_over_time({app="api"} | json | unwrap duration [5m]))
# Average by pod
avg by (pod) (
avg_over_time({app="api"} | json | unwrap duration [5m])
)
# Maximum without specific labels
max without (instance, pod) (
max_over_time({app="api"} | json | unwrap response_size [5m])
)
# Count distinct values (approximate)
count(
count by (user_id) (
{app="api"} | json
)
)
## === ALERTING EXAMPLES ===
# High error rate (>5%)
(
sum(rate({app="api"} | json | level="error" [5m]))
/
sum(rate({app="api"}[5m]))
) > 0.05
# Low log volume (potential issue)
sum(rate({app="api"}[5m])) < 0.1
# High latency (95th percentile >2s)
quantile_over_time(0.95, {app="api"} | json | unwrap duration [5m]) > 2
# No logs received (dead service)
absent_over_time({app="api"}[5m])
# Too many failed logins
sum(rate({app="auth"} | json | event="login_failed" [5m])) > 10
## === ADVANCED QUERIES ===
# Complex filtering with multiple conditions
{app="api"}
| json
| (status_code >= 400 and status_code < 500)
or
(status_code >= 500 and duration > 1)
| method != "HEAD"
| path !~ "/health|/metrics"
# Multi-stage parsing and formatting
{job="nginx"}
| pattern "<ip> - - [<timestamp>] \"<method> <path> <_>\" <status> <size>"
| json
| label_format status_class="{{if ge .status 500}}5xx{{else if ge .status 400}}4xx{{else}}ok{{end}}"
| line_format "{{.status_class}}: {{.method}} {{.path}}"
# Probabilistic top K (for large datasets)
approx_topk(10,
sum by (endpoint) (rate({app="api"}[5m]))
)
# Percentage per status code of total traffic (many-to-one matching against total)
# LogQL supports vector matching modifiers for arithmetic/comparison:
# on(...), ignoring(...), group_left, and group_right.
sum by (status_code) (rate({app="api"} | json [5m]))
/ on() group_left
sum(rate({app="api"}[5m]))
# Percentage per status code within each app (many-to-one matching)
sum by (app, status_code) (rate({job="http-server"} | json [5m]))
/ on(app) group_left
sum by (app) (rate({job="http-server"} | json [5m]))
## === STRUCTURED METADATA (Loki 3.x) ===
# Structured metadata is NOT in stream selector - it comes AFTER the selector
# This enables high-cardinality data without index bloat
# Query logs with structured metadata (correct syntax)
{app="api"} | trace_id="abc123"
# Combine structured metadata with other filters
{app="api"} | trace_id="abc123" | json | level="error"
# Multiple structured metadata filters
{app="api"} | user_id="12345" | request_id="req-abc"
# WRONG: Don't put structured metadata in stream selector!
# {app="api", trace_id="abc123"} # This won't work!
## === QUERY ACCELERATION (Loki 3.x) ===
# ACCELERATED: Structured metadata filter BEFORE parser (bloom filters used)
{cluster="prod"} | detected_level="error" | logfmt | json
# NOT ACCELERATED: Filter AFTER parser (bloom filters skipped)
{cluster="prod"} | logfmt | json | detected_level="error"
# Accelerated with multiple conditions
{app="api"} | trace_id="abc123" | service="payment" | json | level="error"
# Accelerated with OR conditions
{app="api"} | detected_level="error" or detected_level="warn" | json
## === APPROX_TOPK (Probabilistic Top-K) — Loki 3.3+ only ===
# Faster alternative to topk for high-cardinality data
# Returns approximate results, great for large datasets
# REQUIRES: Loki 3.3 or newer — do NOT use when version is unknown or < 3.3
# Approximate top 10 endpoints by request rate
approx_topk(10,
sum by (endpoint) (rate({app="api"}[5m]))
)
# Approximate top 20 users by error count
approx_topk(20,
sum by (user_id) (count_over_time({app="api"} | json | level="error" [1h]))
)
# Use when topk times out or hits series limits
approx_topk(50,
sum by (trace_id) (rate({app="api"}[5m]))
)
## === VECTOR() FOR RELIABLE ALERTING ===
# Ensures a value is always returned (prevents "no data" alert states)
# Always returns a value (0 when no matches)
sum(count_over_time({app="api"} | json | level="error" [5m])) or vector(0)
# Use in alerting rules
sum(rate({app="api"} | json | level="error" [5m])) or vector(0) > 10
# Percentage calculation with fallback
(
sum(rate({app="api"} | json | level="error" [5m])) or vector(0)
)
/
(
sum(rate({app="api"}[5m])) or vector(1)
) * 100
## === __ERROR__ LABEL DEBUGGING ===
# Show only lines that failed to parse
{app="api"} | json | __error__ != ""
# Show only successfully parsed lines (production use)
{app="api"} | json | __error__="" | level="error"
# Debug parse errors with details
{app="api"} | json | __error__ != "" | line_format "ERROR: {{.__error__}} LINE: {{.__line__}}"
# Count errors by parser error type
sum by (__error__) (count_over_time({app="api"} | json | __error__ != "" [5m]))
## === TEMPLATE FUNCTIONS ===
# String manipulation
{app="api"} | json | line_format "{{.path | replace \" \" \"_\" | trunc 50 | upper}}"
# Trim whitespace
{app="api"} | json | line_format "IP: {{.client_ip | trim}}"
# Indent vs nindent
# indent: indents every line in a string
{app="api"} | json | line_format "Message:{{indent 4 .message}}"
# nindent: prepends a newline BEFORE indenting (useful for YAML-like output)
{app="api"} | json | line_format "Details:{{nindent 4 .stack_trace}}"
# nindent is particularly useful for multi-line content
{app="api"} | json | line_format "Error Report:{{nindent 2 .error}}{{nindent 2 .context}}"
# Date formatting
{app="api"} | json | line_format "{{__timestamp__ | date \"2006-01-02T15:04:05\"}}: {{.message}}"
# Math operations
{app="api"} | json | line_format "Duration: {{div .duration_ms 1000}}s"
# Conditional formatting
{app="api"} | json | label_format severity="{{if ge .status_code 500}}critical{{else if ge .status_code 400}}warning{{else}}info{{end}}"
# Access original line
{app="api"} | json | line_format "ORIGINAL: {{__line__ | lower}}"
# Printf formatting
{app="api"} | json | line_format "{{printf \"%-40.40s\" .request_uri}} {{printf \"%5.5s\" .method}}"
# Iterate over JSON array in log
{job="api"} | json | line_format "{{ range $item := fromJson .items }}{{ $item.name }} {{ end }}"
## === LINE MATCH PATTERN OPERATOR (|>) ===
# Faster than regex for pattern matching with wildcards
# <_> is a wildcard for any arbitrary text
# Match pattern with wildcards
{service_name="distributor"} |> "<_> level=debug <_> msg=\"POST /push <_>\""
# Filter out debug logs with pattern
{service_name="api"} !> "<_> level=debug <_>"
# Match HTTP request patterns
{job="nginx"} |> "<_> \"GET /api/<_>\" 200 <_>"
## === DECOLORIZE ===
# Remove ANSI color codes from terminal output
{app="app"} | decolorize
# Decolorize before parsing
{app="app"} | decolorize | json | level="error"
## === UNPACK PARSER ===
# Unpack data that was packed by Promtail's pack stage
{cluster="us-central1", job="myjob"} | unpack
# Unpack and filter by embedded label
{cluster="us-central1", job="myjob"} | unpack | container="myapp"
# Unpack, filter, then parse the original log
{cluster="us-central1", job="myjob"} | unpack | container="myapp" | json
## === ADDITIONAL UNWRAPPED RANGE FUNCTIONS ===
# First value in interval (useful for starting values)
first_over_time({app="api"} | json | unwrap request_count [5m])
# Last value in interval (useful for ending values)
last_over_time({app="api"} | json | unwrap request_count [5m])
# Standard deviation of durations (useful for detecting variability)
stddev_over_time({app="api"} | json | unwrap duration [5m])
# Standard variance of durations
stdvar_over_time({app="api"} | json | unwrap duration [5m])
# Rate counter - treats values as a counter metric (for monotonically increasing values)
rate_counter({app="api"} | json | unwrap total_requests [5m])
# Bytes over time - total bytes in a time range
bytes_over_time({app="api"}[5m])
## === SORTING AND ORDERING ===
# Sort results ascending by value
sort(sum by (app) (rate({job="api"}[5m])))
# Sort results descending by value
sort_desc(sum by (app) (rate({job="api"}[5m])))
# Combine sort with topk for ordered top results
sort_desc(topk(10, sum by (endpoint) (rate({app="api"}[5m]))))
## === LABEL_REPLACE FUNCTION ===
# Extract service name from label using regex capture group
label_replace(
rate({job="api-server", service="payment:v2"} |= "err" [1m]),
"service_name", "$1", "service", "(.*):.*"
)
# Add environment label based on namespace pattern
label_replace(
sum by (namespace) (rate({job="app"}[5m])),
"env", "$1", "namespace", "(prod|staging|dev).*"
)
# Create simplified label from complex one
label_replace(
sum by (pod) (rate({job="kubernetes-pods"}[5m])),
"app", "$1", "pod", "([a-z-]+)-[a-z0-9]+-[a-z0-9]+"
)
## === LABEL_REPLACE CHAINING (Advanced) ===
# Chain multiple label_replace calls for complex transformations
# Example: Extract app, version, and region from pod name "myapp-v2-us-east-1-abc123-xyz789"
label_replace(
label_replace(
label_replace(
sum by (pod) (rate({job="kubernetes-pods"}[5m])),
"app", "$1", "pod", "([a-z-]+)-v[0-9]+-.*"
),
"version", "$1", "pod", "[a-z-]+-v([0-9]+)-.*"
),
"region", "$1", "pod", "[a-z-]+-v[0-9]+-([a-z]+-[a-z]+-[0-9]+)-.*"
)
# Extract team and service from job label like "team-platform/service-api"
label_replace(
label_replace(
sum by (job) (rate({namespace="production"}[5m])),
"team", "$1", "job", "team-([^/]+)/.*"
),
"service", "$1", "job", "[^/]+/service-(.*)"
)
# Create environment label from namespace and add severity from level
label_replace(
label_replace(
sum by (namespace, level) (rate({job="app"} | json [5m])),
"env", "production", "namespace", "prod.*"
),
"severity", "critical", "level", "error|fatal"
)
# Extract domain from URL-based endpoint labels
label_replace(
sum by (endpoint) (rate({app="api"} | json [5m])),
"domain", "$1", "endpoint", "https?://([^/]+)/.*"
)
# Transform pod names to deployment names (strip replicaset hash)
label_replace(
sum by (pod) (rate({namespace="prod"}[5m])),
"deployment", "$1", "pod", "(.*)-[a-f0-9]+-[a-z0-9]+"
)
## === CONVERSION FUNCTIONS ===
# Convert duration strings like "1.5s" or "150ms" to seconds
avg_over_time({app="api"} | json | unwrap duration_seconds(response_time) [5m])
# Convert byte strings like "1.5KB" or "10MB" to bytes
sum_over_time({app="api"} | json | unwrap bytes(payload_size) [5m])
## === FLOAT TEMPLATE FUNCTIONS ===
# Division with float result
{app="api"} | json | line_format "Duration: {{divf .duration_ns 1000000}}ms"
# Subtraction with floats
{app="api"} | json | line_format "Change: {{subf .current .previous}}"
# Floor and ceiling
{app="api"} | json | line_format "Floor: {{floor .value}} Ceil: {{ceil .value}}"
# Round to 2 decimal places
{app="api"} | json | line_format "Rounded: {{round .percentage 2}}%"
## === REGEX TEMPLATE FUNCTIONS ===
# Replace with regex capture groups
{app="api"} | json | line_format "{{regexReplaceAll \"user_(\\\\d+)\" .message \"User ID: $1\"}}"
# Literal replacement (no capture group expansion)
{app="api"} | json | line_format "{{regexReplaceAllLiteral \"error\" .message \"ERROR\"}}"
## === AUTOMATIC LABELS (service_name and detected_level) ===
# Loki automatically populates certain labels to improve log exploration
## service_name Label (Auto-populated)
# - Auto-populated by Loki when no service name is provided
# - Uses container name as fallback if not specified
# - Used in Grafana's Logs Drilldown feature
# - Can be customized via discover_service_name in limits_config
# Query by auto-generated service_name
{service_name="my-api"}
# Combine service_name with other filters
{service_name="my-api"} | json | level="error"
# Error rate by service_name
sum by (service_name) (rate({namespace="production"} | json | level="error" [5m]))
# Top services by error count
topk(10, sum by (service_name) (count_over_time({namespace="prod"} | json | level="error" [1h])))
## detected_level Label (Structured Metadata - Auto-detected)
# - Auto-detected when discover_log_levels: true is configured
# - Stored as structured metadata (NOT indexed)
# - Values: debug, info, warn, error, critical, fatal
# - Requires allow_structured_metadata: true in limits_config
# - Place BEFORE parsers for query acceleration with bloom filters!
# Query by auto-detected log level (accelerated with bloom filters)
{cluster="prod"} | detected_level="error" | json
# Combine detected_level with other structured metadata
{app="api"} | detected_level="warn" | trace_id="abc123" | json
# Multiple detected_level values with OR (accelerated)
{app="api"} | detected_level="error" or detected_level="critical" | json
# Error count using detected_level
sum(count_over_time({namespace="prod"} | detected_level="error" | json [5m]))
# Error rate by detected_level
sum by (detected_level) (rate({app="api"} | detected_level!="" | json [5m]))
# WRONG: detected_level AFTER parser loses acceleration!
# {cluster="prod"} | json | detected_level="error" # NOT accelerated
# CORRECT: detected_level BEFORE parser (accelerated)
{cluster="prod"} | detected_level="error" | json
## === GRAFANA ALLOY / PROMTAIL MIGRATION ===
# Note: Promtail is deprecated in favor of Grafana Alloy
# Commercial support for Promtail ends February 28, 2026
# For new deployments, use Grafana Alloy instead of Promtail
# Query logs collected by Alloy (same LogQL syntax)
{collector="alloy"}
# Query logs with Alloy-specific labels
{job="alloy"} | json | level="error"
LogQL Best Practices
This document outlines best practices for writing efficient, maintainable, and performant LogQL queries in Grafana Loki.
Query Structure and Performance
1. Use Specific Stream Selectors
Always use the most specific label selectors possible to reduce the number of streams Loki needs to search.
Good:
{namespace="production", app="api-server", environment="prod"}Bad:
{namespace="production"} # Too broad, searches many streamsWhy: Loki indexes logs by label combinations (streams). More specific selectors mean fewer streams to search, resulting in faster queries.
2. Order Operations Efficiently
Apply filters in the most efficient order: stream selector → line filters → parser → label filters → aggregations.
Good:
{job="nginx"} |= "error" | json | status_code >= 500 | sum(count_over_time([5m]))Bad:
{job="nginx"} | json | status_code >= 500 |= "error" # Parse before line filterWhy: Line filters are fast and work on raw log lines. Parsers are more expensive. Apply cheap operations first to reduce data early.
3. Use Line Filters Before Parsing
Filter out irrelevant log lines before parsing to reduce computational overhead.
Good:
{app="api"} |= "error" | json | level="error"Bad:
{app="api"} | json | level="error" # Parses all logs, not just errorsWhy: Line filters (|=, !=, |~, !~) are extremely fast string operations. Parsing (json, logfmt, regexp) is more expensive.
4. Avoid Complex Regex When Simple Matching Works
Use exact string matching when possible instead of regex.
Good:
{job="app"} |= "ERROR:" # Fast string matchBad:
{job="app"} |~ "ERROR:" # Slower regex match for simple stringWhy: Regex matching requires compilation and more complex pattern matching. Simple string contains is significantly faster.
5. Use Appropriate Time Ranges
Use the shortest time range that satisfies your requirements.
Good:
rate({app="api"}[1m]) # For real-time dashboards
rate({app="api"}[1h]) # For trend analysisBad:
rate({app="api"}[24h]) # Unnecessarily long for real-time monitoringWhy: Larger time ranges mean more data to process. Match the range to your use case.
Label Management
6. Understand Label vs Line Filter Trade-offs
Use labels for indexed dimensions, line filters for unique values.
Good (using line filter for unique ID):
{app="api"} |= "trace_id=abc123"Bad (would create high cardinality if trace_id was a label):
{app="api", trace_id="abc123"} # Don't do this!Why: Labels create separate streams and indexes. High cardinality labels (user IDs, trace IDs, session IDs) create too many streams, degrading performance.
7. Keep Cardinality Low
Avoid using high-cardinality data as labels in stream selectors.
High cardinality fields (use line filters instead):
- user_id
- trace_id
- request_id
- session_id
- ip_address (individual IPs)
- timestamp
Good cardinality fields (suitable for labels):
- namespace
- app
- environment
- cluster
- level (error, warn, info)
- pod (in moderation)
- job
- host (in moderation)
Why: Each unique combination of labels creates a new stream. Too many streams overwhelm Loki's indexing.
8. Use Label Operations Wisely
Drop unnecessary labels to reduce series cardinality in metric queries.
Good:
{app="api"} | json | drop instance, pod | sum by (namespace, app) (rate([5m]))Why: Fewer labels in results = fewer time series = better performance and lower memory usage.
Parsing Best Practices
9. Choose the Right Parser
Use the most appropriate parser for your log format.
| Log Format | Parser | Example |
|---|---|---|
| Custom patterns | pattern | `{app="nginx"} \ |
| key=value pairs | logfmt | `{app="api"} \ |
| key=value (strict) | logfmt --strict | `{app="api"} \ |
| JSON | json | `{app="api"} \ |
| JSON (specific fields) | json | `{app="api"} \ |
| Complex regex | regexp | `{app="api"} \ |
Performance order (fastest to slowest): pattern > logfmt > json > regexp
Why this order matters:
- pattern: Simple string matching with placeholders, fastest execution
- logfmt: Optimized key=value parsing, very efficient
- json: Full JSON parsing, moderate overhead
- regexp: Regex compilation and matching, slowest but most flexible
Why: Simpler parsers are faster. JSON and logfmt are optimized. Pattern is faster than regex for simple cases.
9a. Use logfmt Parser Flags When Needed
The logfmt parser supports optional flags for handling edge cases:
`--strict` flag:
# Fail on malformed key=value pairs (stops scanning on error)
{app="api"} | logfmt --strict
# Use when you need to detect malformed log entries
{app="api"} | logfmt --strict | __error__ != ""`--keep-empty` flag:
# Retain standalone keys as labels with empty string value
{app="api"} | logfmt --keep-empty
# Combine flags
{app="api"} | logfmt --strict --keep-emptyWhen to use:
--strict: When log quality matters and you want to detect malformed entries--keep-empty: When logs have standalone keys (no values) that need to be preserved
Why: By default, logfmt is non-strict (skips invalid tokens) which is more lenient but may hide log quality issues.
9b. Use JSON Parser Parameter Extraction for Performance
Extract only the fields you need instead of parsing entire JSON:
Good (extract specific fields):
{app="api"} | json status="response.code", method="request.method"Less efficient (parse all fields):
{app="api"} | jsonSupported access patterns:
- Dot notation:
| json method="request.method" - Bracket notation:
| json ua="headers[\"User-Agent\"]" - Array access:
| json first="items[0]" - Combined:
| json item="data.items[0].name"
Why: Extracting fewer fields reduces parsing overhead and memory usage.
10. Parse Only What You Need
If you only need specific fields, extract just those fields.
Good:
{app="api"} | json level, message, status_codeBetter than:
{app="api"} | json # Parses all fieldsWhy: Extracting fewer fields reduces parsing overhead and memory usage.
11. Use Pattern Parser for Simple Cases
Pattern parser is faster than regex for straightforward field extraction.
Good:
{job="nginx"} | pattern "<ip> - - [<timestamp>] \"<method> <path> <_>\" <status>"Avoid (unless necessary):
{job="nginx"} | regexp "(?P<ip>\\S+) .* (?P<method>\\w+) (?P<path>\\S+).*"Why: Pattern parser is simpler and faster for structured formats.
Aggregation Best Practices
12. Use Appropriate Aggregation Functions
Choose the right function for your metric type.
| Metric Type | Function | Use Case |
|---|---|---|
| Count logs | count_over_time() | Number of log lines |
| Event rate | rate(), bytes_rate() | Events per second |
| Numeric extraction | unwrap + sum_over_time() | Sum of values |
| Percentiles | quantile_over_time() | Latency, duration |
| Statistics | avg_over_time(), max_over_time(), min_over_time() | Averages, extremes |
13. Aggregate Early and Often
Reduce data volume as early as possible.
Good:
sum by (namespace) (
count_over_time({app="api"} | json | level="error" [5m])
)Why: Aggregating reduces the number of time series, improving query performance.
14. Use by Instead of without When Possible
Explicitly specify labels to keep rather than labels to remove.
Good:
sum by (namespace, app) (rate({job="kubernetes-pods"}[5m]))Less efficient:
sum without (pod, instance, node) (rate({job="kubernetes-pods"}[5m]))Why: by is more explicit and often results in fewer output series.
Query Optimization
15. Avoid Expensive Operations in Inner Loops
Don't use regex or complex parsing inside frequently-evaluated contexts.
Good:
sum(rate({app="api"} |= "error" [5m])) # Filter firstBad:
sum(rate({app="api"} | regexp "complex.*pattern" [5m])) # Regex on every line16. Use Metric Queries for Dashboards
For dashboard panels, use metric queries (aggregations) rather than log queries.
Good (for time series panel):
rate({app="api"}[5m])Bad (for time series panel):
{app="api"} # Returns log lines, not metricsWhy: Metric queries return time series data suitable for graphing.
17. Limit Log Query Results
When querying for log lines (not metrics), limit the result set.
Important: The limit is an API parameter, not a LogQL pipeline operator. Set it via:
- API:
/loki/api/v1/query_range?query={...}&limit=100 - Grafana UI: "Line limit" field in the query editor (default: 1000)
- logcli:
--limit=100flag
Good:
# Using logcli
logcli query '{app="api"} | json | level="error"' --limit=100
# Using API
curl -G "http://localhost:3100/loki/api/v1/query_range" \
--data-urlencode 'query={app="api"} | json | level="error"' \
--data-urlencode 'limit=100'Why: Returning thousands of log lines is slow and resource-intensive. Always set appropriate limits for log queries.
18. Use __error__="" to Filter Parse Errors
When parsing, filter out lines that fail to parse to get clean results.
Good:
{app="api"} | json | __error__="" | level="error"Why: Parse errors create __error__ labels. Filtering them out gives you only successfully parsed logs.
Alerting Best Practices
19. Use Metric Queries for Alerts
Alerts require numeric values. Always use metric queries (aggregations).
Good:
sum(rate({app="api"} | json | level="error" [5m])) > 10Bad:
{app="api"} | json | level="error" # Returns logs, not metrics20. Include Meaningful Thresholds
Set explicit, meaningful thresholds for alerting.
Good:
(
sum(rate({app="api"} | json | level="error" [5m]))
/
sum(rate({app="api"}[5m]))
) > 0.05 # Alert if error rate > 5%Why: Thresholds should be based on SLOs or historical baselines.
21. Use absent_over_time for Missing Logs
Detect when logs stop coming (potential service outage).
Good:
absent_over_time({app="critical-service"}[5m])Why: This returns 1 when no logs match in the time range, indicating a potential problem.
Security and Sensitive Data
22. Don't Log Sensitive Information
Avoid logging sensitive data that could appear in LogQL query results.
Avoid in logs:
- Passwords
- API keys
- Tokens
- Credit card numbers
- PII (personally identifiable information)
If you must log sensitive data:
- Use structured metadata (not indexed)
- Redact before ingestion
- Use Loki's data retention policies
- Restrict access with Loki's multi-tenancy
23. Use Structured Metadata for High-Cardinality Data
Store high-cardinality data as structured metadata, not labels.
Good:
# In your log shipper config
structured_metadata:
trace_id: ${TRACE_ID}
user_id: ${USER_ID}Then query:
{app="api"} | trace_id="abc123"Why: Structured metadata is not indexed, avoiding cardinality issues.
Maintenance and Debugging
24. Test Queries Incrementally
Build complex queries step by step, testing each stage.
Approach:
# Step 1: Test stream selector
{app="api"}
# Step 2: Add line filter
{app="api"} |= "error"
# Step 3: Add parser
{app="api"} |= "error" | json
# Step 4: Add label filter
{app="api"} |= "error" | json | status_code >= 500
# Step 5: Add aggregation
sum(count_over_time({app="api"} |= "error" | json | status_code >= 500 [5m]))Why: Incremental testing helps identify issues early and understand query behavior.
25. Use line_format for Debugging
Format log output to see extracted fields during development.
Debugging query:
{app="api"} | json | line_format "level={{.level}} status={{.status_code}} message={{.message}}"Why: Makes it easy to see what fields were extracted and their values.
26. Comment Complex Queries
Use LogQL comments to document complex queries.
Good:
# Calculate 5xx error rate as percentage
# Alerts when > 5% for SLO compliance
(
sum(rate({app="api"} | json | status_code >= 500 [5m]))
/
sum(rate({app="api"}[5m]))
) * 100 > 5Why: Comments help team members understand query intent and logic.
Performance Tuning
27. Use Query Splitting for Large Time Ranges
For very large time ranges, consider splitting queries or using downsampling.
Instead of:
sum(count_over_time({app="api"}[30d])) # Very expensiveConsider:
- Using Loki's query splitting (automatic in recent versions)
- Using recording rules for frequently-queried metrics
- Adjusting retention policies
28. Leverage Loki's Query Parallelization
Recent Loki versions automatically parallelize queries. Structure queries to take advantage:
Good (parallelizable):
sum by (namespace) (rate({job="kubernetes-pods"}[5m]))Why: Loki can process different namespaces in parallel.
29. Use Appropriate Step Sizes
For metric queries over long time ranges, use appropriate step sizes.
Good:
# For 24h dashboard, use 1m step
rate({app="api"}[5m]) # With 1m step in Grafana
# For 7d dashboard, use 5m or 15m step
rate({app="api"}[15m]) # With 5m stepWhy: Smaller steps = more data points = slower queries. Match resolution to your needs.
Structured Metadata (Loki 3.x)
35. Use Structured Metadata for High-Cardinality Data
Structured metadata is metadata attached to logs without indexing. Introduced in Loki 3.0.
What it is:
- Metadata attached to logs that is NOT indexed
- Ideal for high-cardinality data (trace_id, user_id, request_id, pod names)
- Avoids index bloat and cardinality explosion
- Automatically extracted as labels in query results
Key differences from labels:
- Labels are indexed → fast stream selection, but high cardinality is expensive
- Structured metadata is NOT indexed → no cardinality impact, but requires scanning
Query syntax:
# Filter by structured metadata (AFTER stream selector, not inside it!)
{app="api"} | trace_id="abc123"
# Combine multiple structured metadata filters
{app="api"} | trace_id="abc123" | user_id="user456"
# Use with other filters
{app="api"} | trace_id="abc123" | json | level="error"WRONG (structured metadata is not a label):
{app="api", trace_id="abc123"} # This won't work!When to use:
- OpenTelemetry data (trace IDs, span IDs)
- High-cardinality identifiers (user IDs, request IDs, session IDs)
- Kubernetes metadata (pod UIDs, container IDs)
- Any data that would create too many unique label combinations
Configuration (requires Loki 3.0+ with schema v13+):
limits_config:
allow_structured_metadata: true36. Query Acceleration with Structured Metadata
Loki 3.x can accelerate queries using bloom filters when structured metadata filters are placed correctly.
CRITICAL: Filter Order Matters for Acceleration
Accelerated (bloom filters used):
{cluster="prod"} | detected_level="error" | logfmt | jsonThe structured metadata filter comes BEFORE parsers.
NOT Accelerated (bloom filters NOT used):
{cluster="prod"} | logfmt | json | detected_level="error"The filter comes AFTER parsers, preventing acceleration.
Rules for query acceleration: 1. Use string equality filters: | key="value" 2. Place structured metadata filters BEFORE any parser expressions 3. Filters BEFORE logfmt, json, pattern, regexp, label_format, label_replace
Supported filter patterns:
# Simple equality (accelerated)
{app="api"} | trace_id="abc123" | json
# Multiple filters with OR (accelerated)
{app="api"} | detected_level="error" or detected_level="warn" | json
# Multiple filters with AND (accelerated)
{app="api"} | service="api" and environment="prod" | jsonWhy this matters:
- Bloom filters can skip chunks that definitely don't contain the data
- Significant performance improvement for "needle in haystack" queries
- Essential for large-scale deployments (75TB+ monthly logs)
__error__ Label Debugging
37. Debug Parse Errors with __error__ Label
When parsing fails, Loki creates an __error__ label with the error type.
Show only lines that failed to parse:
{app="api"} | json | __error__ != ""Show only successfully parsed lines (filter OUT errors):
{app="api"} | json | __error__=""Common error values:
JSONParserErr- Invalid JSONLogfmtParserErr- Invalid logfmtPatternParserErr- Pattern didn't matchRegexpParserErr- Regex didn't match
Debugging workflow:
# Step 1: See which lines are failing
{app="api"} | json | __error__ != "" | line_format "ERROR: {{.__error__}} LINE: {{.__line__}}"
# Step 2: Count errors by type
sum by (__error__) (count_over_time({app="api"} | json | __error__ != "" [5m]))
# Step 3: Production query (exclude errors)
{app="api"} | json | __error__="" | level="error"Why this matters:
- Silent parse failures can cause missing data
- Always filter
__error__=""in production dashboards - Use error queries to debug log format issues
Recording Rules
38. Use Recording Rules for Expensive Queries
Recording rules precompute expensive queries and store results as metrics.
When to use recording rules:
- Dashboard queries that run frequently
- Complex aggregations over large datasets
- Queries that would otherwise time out
- Per-tenant alerting in multi-tenant systems
Example recording rule configuration:
# /tmp/loki/rules/<tenant-id>/rules.yaml
groups:
- name: error_rates
interval: 1m
rules:
# Record error rate per app
- record: app:error_rate:1m
expr: |
sum by (app) (
rate({job="kubernetes-pods"} | json | level="error" [1m])
)
labels:
source: loki_recording_rule
# Record request rate per namespace
- record: namespace:request_rate:5m
expr: |
sum by (namespace) (
rate({job="kubernetes-pods"}[5m])
)
- name: alerting_rules
interval: 1m
rules:
- alert: HighErrorRate
expr: |
(
sum by (app) (rate({job="app"} | json | level="error" [5m]))
/
sum by (app) (rate({job="app"}[5m]))
) > 0.05
for: 10m
labels:
severity: warning
annotations:
summary: "High error rate for {{ $labels.app }}"
description: "Error rate is {{ $value | printf \"%.2f\" }}%"Ruler configuration:
ruler:
storage:
type: local
local:
directory: /tmp/loki/rules
rule_path: /tmp/scratch
alertmanager_url: http://alertmanager:9093
enable_api: true
ring:
kvstore:
store: inmemoryBenefits:
- Reduces query load on Loki
- Faster dashboard loading
- Consistent results across queries
- Enables alerting on complex conditions
39. Use vector() for Reliable Alerting
The vector() function ensures alerting rules always return a value.
Problem: When no logs match, the query returns nothing, causing "no data" alert states.
Solution:
# Always returns a value (0 when no matches)
sum(count_over_time({app="api"} | json | level="error" [5m])) or vector(0)
# Use in alerting rule
sum(rate({app="api"} | json | level="error" [5m])) or vector(0) > 10Why this matters:
- Prevents flapping alerts due to "no data" states
- Provides consistent behavior for sparse logs
- Essential for reliable alerting on low-volume services
Anti-Patterns to Avoid
30. Don't Use High-Cardinality Labels
Never do this:
{app="api", user_id="12345"} # user_id is high cardinality!Do this instead:
{app="api"} | json | user_id="12345"31. Don't Parse Multiple Times
Inefficient:
{app="api"} | json | json | json # Multiple parsersEfficient:
{app="api"} | json # Once is enough32. Don't Use Regex for Simple String Matching
Inefficient:
{app="api"} |~ "GET" # Regex for simple stringEfficient:
{app="api"} |= "GET" # Fast string contains33. Don't Aggregate Without Labels
Inefficient (no grouping):
sum(rate({app="api"}[5m])) # Single time seriesBetter (grouped by useful dimensions):
sum by (namespace, app, environment) (rate({app="api"}[5m]))34. Don't Use Very Long Time Ranges in range vectors
Inefficient:
rate({app="api"}[24h]) # 24 hours of data per calculationEfficient:
rate({app="api"}[5m]) # 5 minutes of data per calculationWhy: Range vectors determine how much historical data each point calculation needs.
Important Notes About Non-Existent Features
LogQL Does NOT Have dedup or distinct Operators
No `| dedup` syntax: Deduplication is handled at the UI level in Grafana's Explore panel, not in LogQL itself.
No `| distinct` syntax: A distinct operator was proposed in PR #8662 but was reverted before public release due to issues with query splitting, sharding, and metric query compatibility. The proposed syntax {job="app"} | distinct label is NOT available in current Loki versions.
For programmatic deduplication, use metric aggregations:
# Count unique messages
sum by (message) (count_over_time({app="api"} | json [5m])) > 0
# Count distinct values of a label
count(count by (user_id) ({app="api"} | json))LogQL limit is an API Parameter, NOT a Pipeline Operator
There is no | limit 100 syntax in LogQL. The limit is set via:
- API parameter:
&limit=100 - Grafana UI: "Line limit" field
- logcli:
--limit=100flag
See Best Practice #17 for details.
Summary Checklist
When writing LogQL queries, ensure:
- [ ] Stream selectors are as specific as possible
- [ ] Line filters come before parsers
- [ ] Exact string matching is used instead of regex when possible
- [ ] Time ranges are appropriate for the use case
- [ ] High-cardinality data is not used as labels
- [ ] The right parser is chosen for the log format
- [ ] Only necessary fields are extracted
- [ ] Aggregations are used for metric queries
- [ ] Results are limited for log queries
- [ ] Queries are tested incrementally
- [ ] Complex queries are documented with comments
- [ ]
sortorsort_descused for ordered results - [ ]
label_replaceused for regex-based label manipulation in metrics - [ ]
vector(0)used as fallback in alerting rules
Additional Resources
Related Skills
- loki-config-generator: For configuring Loki server
- promql-generator: For PromQL queries (similar concepts)
- fluentbit-generator: For log collection pipelines
#!/usr/bin/env bash
#
# Run logql-generator regression checks.
# - Static contract checks always run.
# - Runtime Loki checks are controlled by RUN_LOKI_RUNTIME_TESTS:
# auto (default): run only when Docker is available
# 1/true: require runtime checks (fail if Docker is unavailable)
# 0/false: skip runtime checks
#
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly SKILL_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
readonly TEST_DIR="$SKILL_DIR/tests"
if [[ ! -d "$TEST_DIR" ]]; then
echo "FAIL: tests directory not found: $TEST_DIR" >&2
exit 1
fi
RUN_MODE="${RUN_LOKI_RUNTIME_TESTS:-auto}"
echo "Running logql-generator regression checks..."
echo "RUN_LOKI_RUNTIME_TESTS=${RUN_MODE}"
echo ""
PYTHONDONTWRITEBYTECODE=1 \
RUN_LOKI_RUNTIME_TESTS="$RUN_MODE" \
python3 -m unittest discover -s "$TEST_DIR" -p "test_*.py" -v
echo ""
echo "All logql-generator regression checks finished."
#!/usr/bin/env python3
"""Runtime Loki integration tests for logql-generator query regressions."""
from __future__ import annotations
import json
import os
import shutil
import socket
import subprocess
import time
import unittest
from urllib import error, parse, request
RUN_MODE = os.getenv("RUN_LOKI_RUNTIME_TESTS", "auto").strip().lower()
LOKI_IMAGE = os.getenv("LOKI_IMAGE", "grafana/loki:3.6.2").strip()
STARTUP_TIMEOUT_SECONDS = int(os.getenv("LOKI_STARTUP_TIMEOUT_SECONDS", "60"))
QUERY_TIMEOUT_SECONDS = int(os.getenv("LOKI_QUERY_TIMEOUT_SECONDS", "25"))
_REQUIRE_VALUES = {"1", "true", "yes", "required"}
_SKIP_VALUES = {"0", "false", "no", "off", "skip"}
class LokiRuntimeIntegrationTests(unittest.TestCase):
"""Validate key query examples against a real ephemeral Loki runtime."""
container_name: str | None = None
base_url: str | None = None
@staticmethod
def _docker_available() -> bool:
if shutil.which("docker") is None:
return False
try:
subprocess.run(
["docker", "info"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except (OSError, subprocess.CalledProcessError):
return False
return True
@staticmethod
def _reserve_host_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return int(sock.getsockname()[1])
@classmethod
def _stop_container(cls) -> None:
if not cls.container_name:
return
subprocess.run(
["docker", "rm", "-f", cls.container_name],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
cls.container_name = None
cls.base_url = None
@classmethod
def setUpClass(cls) -> None:
if RUN_MODE in _SKIP_VALUES:
raise unittest.SkipTest(
"Runtime Loki tests skipped by RUN_LOKI_RUNTIME_TESTS."
)
docker_ready = cls._docker_available()
if RUN_MODE in _REQUIRE_VALUES and not docker_ready:
raise RuntimeError(
"RUN_LOKI_RUNTIME_TESTS requires Docker, but Docker is unavailable."
)
if RUN_MODE not in _REQUIRE_VALUES and not docker_ready:
raise unittest.SkipTest(
"Docker unavailable; skipping runtime Loki tests (auto mode)."
)
host_port = cls._reserve_host_port()
cls.container_name = f"logql-generator-loki-{os.getpid()}-{int(time.time())}"
cls.base_url = f"http://127.0.0.1:{host_port}"
try:
subprocess.run(
[
"docker",
"run",
"-d",
"--rm",
"--name",
cls.container_name,
"-p",
f"{host_port}:3100",
LOKI_IMAGE,
"-config.file=/etc/loki/local-config.yaml",
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
)
cls._wait_until_ready()
cls._push_sample_logs()
except Exception:
cls._stop_container()
raise
@classmethod
def tearDownClass(cls) -> None:
cls._stop_container()
@classmethod
def _wait_until_ready(cls) -> None:
assert cls.base_url is not None
ready_url = f"{cls.base_url}/ready"
deadline = time.time() + STARTUP_TIMEOUT_SECONDS
last_error: str | None = None
while time.time() < deadline:
try:
with request.urlopen(ready_url, timeout=4) as response:
body = response.read().decode("utf-8", errors="ignore").lower()
if response.status == 200 and "ready" in body:
return
except error.HTTPError as exc: # pragma: no cover - retry loop
try:
exc.read()
finally:
exc.close()
last_error = f"HTTP {exc.code}"
except Exception as exc: # pragma: no cover - retry loop
last_error = str(exc)
time.sleep(1)
raise RuntimeError(f"Loki did not become ready in time: {last_error}")
@classmethod
def _push_sample_logs(cls) -> None:
assert cls.base_url is not None
now_ns = time.time_ns()
# Keep log lines within a recent 5m range window for rate()/bytes_over_time().
samples = {
"streams": [
{
"stream": {"app": "api", "job": "http-server"},
"values": [
[str(now_ns - 90_000_000_000), '{"status_code":200,"duration":0.12,"level":"info"}'],
[str(now_ns - 60_000_000_000), '{"status_code":500,"duration":1.42,"level":"error"}'],
[str(now_ns - 30_000_000_000), '{"status_code":500,"duration":0.98,"level":"error"}'],
],
},
{
"stream": {"app": "billing", "job": "http-server"},
"values": [
[str(now_ns - 85_000_000_000), '{"status_code":200,"duration":0.10,"level":"info"}'],
[str(now_ns - 55_000_000_000), '{"status_code":404,"duration":0.23,"level":"warn"}'],
[str(now_ns - 25_000_000_000), '{"status_code":500,"duration":1.33,"level":"error"}'],
],
},
]
}
payload = json.dumps(samples, separators=(",", ":")).encode("utf-8")
req = request.Request(
f"{cls.base_url}/loki/api/v1/push",
data=payload,
method="POST",
headers={"Content-Type": "application/json"},
)
with request.urlopen(req, timeout=10) as response:
if response.status != 204:
raise RuntimeError(f"Unexpected Loki push status code: {response.status}")
def _query(self, query: str) -> list[dict]:
assert self.base_url is not None
url = f"{self.base_url}/loki/api/v1/query?{parse.urlencode({'query': query})}"
req = request.Request(url, method="GET")
try:
with request.urlopen(req, timeout=10) as response:
payload = json.loads(response.read().decode("utf-8"))
except error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="ignore")
raise AssertionError(f"Loki query failed ({exc.code}): {body}") from exc
self.assertEqual(payload.get("status"), "success", msg=str(payload))
return payload.get("data", {}).get("result", [])
def _query_until_non_empty(self, query: str) -> list[dict]:
deadline = time.time() + QUERY_TIMEOUT_SECONDS
last_error: Exception | None = None
last_result: list[dict] = []
while time.time() < deadline:
try:
last_result = self._query(query)
if last_result:
return last_result
except Exception as exc: # pragma: no cover - retry loop
last_error = exc
time.sleep(1)
if last_error is not None:
raise AssertionError(f"Query did not stabilize: {last_error}") from last_error
raise AssertionError(f"Query returned no results within timeout: {query}")
def test_ratio_against_total_with_on_group_left_executes(self) -> None:
query = (
'sum by (status_code) (rate({app="api"} | json [5m]))'
" / on() group_left "
'sum(rate({app="api"}[5m]))'
)
result = self._query_until_non_empty(query)
self.assertGreaterEqual(len(result), 2)
for series in result:
self.assertIn("status_code", series.get("metric", {}))
def test_many_to_one_ratio_with_group_left_executes(self) -> None:
query = (
'sum by (app, status_code) (rate({job="http-server"} | json [5m]))'
" / on(app) group_left "
'sum by (app) (rate({job="http-server"} | json [5m]))'
)
result = self._query_until_non_empty(query)
apps = set()
for series in result:
metric = series.get("metric", {})
self.assertIn("app", metric)
self.assertIn("status_code", metric)
apps.add(metric["app"])
self.assertIn("api", apps)
self.assertIn("billing", apps)
def test_bytes_over_time_executes_without_unwrap(self) -> None:
query = 'bytes_over_time({app="api"}[5m])'
result = self._query_until_non_empty(query)
self.assertTrue(any(series.get("metric", {}).get("app") == "api" for series in result))
if __name__ == "__main__":
unittest.main()
#!/usr/bin/env python3
"""Regression tests for logql-generator documentation contracts."""
from pathlib import Path
import re
import unittest
SKILL_DIR = Path(__file__).resolve().parent.parent
COMMON_QUERIES = SKILL_DIR / "examples" / "common_queries.logql"
def _resolve_skill_md() -> Path:
candidate = SKILL_DIR / "SKILL.md"
if candidate.exists():
return candidate
raise FileNotFoundError(f"Could not find skill markdown file: {candidate}")
SKILL_MD = _resolve_skill_md()
def _between(text: str, start_marker: str, end_marker: str) -> str:
start = text.find(start_marker)
end = text.find(end_marker, start + len(start_marker))
if start == -1 or end == -1:
raise AssertionError(
f"Could not find section boundaries: {start_marker!r} -> {end_marker!r}"
)
return text[start:end]
class TestVectorMatchingGuidance(unittest.TestCase):
"""Ensure ratio examples and guidance reflect actual LogQL vector matching behavior."""
@classmethod
def setUpClass(cls) -> None:
cls.examples_text = COMMON_QUERIES.read_text(encoding="utf-8")
def test_does_not_claim_vector_matching_is_unsupported(self) -> None:
bad_claim = re.compile(
r"does\s+not\s+support.*on\(\).*group_left",
re.IGNORECASE | re.DOTALL,
)
self.assertIsNone(
bad_claim.search(self.examples_text),
"Examples must not claim that on()/group_left() are unsupported in LogQL.",
)
def test_has_ratio_example_with_on_group_left_against_total(self) -> None:
self.assertRegex(
self.examples_text,
re.compile(
r"sum by \(status_code\)\s*\(rate\(\{app=\"api\"\} \| json \[5m\]\)\)\s*"
r"/ on\(\) group_left\s*sum\(rate\(\{app=\"api\"\}\[5m\]\)\)",
re.DOTALL,
),
)
def test_has_many_to_one_ratio_example_with_group_left(self) -> None:
self.assertRegex(
self.examples_text,
re.compile(
r"sum by \(app, status_code\)\s*\(rate\(\{job=\"http-server\"\} \| json \[5m\]\)\)\s*"
r"/ on\(app\) group_left\s*"
r"sum by \(app\)\s*\(rate\(\{job=\"http-server\"\} \| json \[5m\]\)\)",
re.DOTALL,
),
)
class TestBytesOverTimePlacement(unittest.TestCase):
"""Ensure bytes_over_time remains classified as a log-range aggregation."""
@classmethod
def setUpClass(cls) -> None:
cls.skill_text = SKILL_MD.read_text(encoding="utf-8")
cls.log_range_section = _between(
cls.skill_text,
"### Log Range Aggregations",
"### Unwrapped Range Aggregations",
)
cls.unwrapped_section = _between(
cls.skill_text,
"### Unwrapped Range Aggregations",
"### Aggregation Operators",
)
def test_bytes_over_time_is_listed_in_log_range_section(self) -> None:
self.assertIn("`bytes_over_time(log-range)`", self.log_range_section)
def test_bytes_over_time_is_not_listed_in_unwrapped_section(self) -> None:
self.assertNotIn("bytes_over_time", self.unwrapped_section)
def test_skill_has_bytes_over_time_usage_rule(self) -> None:
self.assertIn(
"Use `bytes_over_time(<log-range>)` for raw log-byte volume.",
self.skill_text,
)
self.assertIn(
"Use `| unwrap bytes(field)` with unwrapped range aggregations",
self.skill_text,
)
if __name__ == "__main__":
unittest.main()