Loki LogQL Query Parse Error Fix
In this tutorial, you'll learn about Loki LogQL Query Parse Error Fix. We cover key concepts, practical examples, and best practices.
Grafana shows Query error: parse error at line 1 — your LogQL query has a syntax error, missing stream selector, or an invalid filter expression.
The Problem
# WRONG — no stream selector
rate({5m})
parse error at line 1: no stream selector
LogQL queries must start with a log stream selector ({label="value"}). The pipeline operations (rate, count_over_time, etc.) come after the stream selector.
Step-by-Step Fix
1. Always start with a stream selector
# RIGHT — stream selector then pipeline
{app="myapp"} |= "error"
2. Use correct label matchers
# Exact match
{app="myapp"}
# Regex match
{app=~"myapp|backend"}
# Not equal
{app!="frontend"}
# Not matching regex
{app!~"internal-.*"}
3. Add pipeline stages correctly
# Line filter (fastest)
{app="myapp"} |= "error"
# Label filter (after logfmt/json parsing)
{app="myapp"} | logfmt | level = "error"
# Line filter + label filter
{app="myapp"} |= "ERROR" | json | status >= 500
# Metric query with aggregation
sum by(level) (
count_over_time({app="myapp"} |= "error" [5m])
)
4. Handle JSON logs properly
# Parse JSON fields
{app="myapp"} | json | level = "error"
# Extract specific fields
{app="myapp"} | json | line_format "{{.message}}"
# Nested JSON JSON
{app="myapp"} | json | metadata = "{{.metadata}}" | json
5. Use unwrap for metric queries with values
# Rate based on a numeric value
sum by(level) (
rate({app="myapp"} | json | unwrap duration [5m])
)
Expected output:
{app="myapp"} |= "error" | json | level = "error"
✓ Query parsed successfully
✓ 234 results in the last 15 minutes
Prevention Tips
- Always start LogQL queries with
{label="value"} - Use
|=for simple text search (most efficient) - Use
| jsonor| logfmtbefore filtering parsed fields - Test queries in Grafana Explore before building dashboards
- Use
count_over_timefor log volume,ratefor log frequency
Common Mistakes with log query
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world LOKI code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro