LogQL Cheat Sheet

LogQL is the query language used in Grafana’s Loki, a horizontally scalable, multi-tenant log aggregation system. It allows you to query and analyze logs efficiently. Here’s a cheat sheet to help you get started with LogQL:

Basic Queries

Search for Logs:

{job="app"} |= "error"
  • Searches for logs in the “app” job containing the word “error.”

Filtering

Filter by Labels:

{job="app", level="error"}
  • Filters logs from the “app” job with the label “level” set to “error.”

Time Range

Specify Time Range:

{job="app"} |~ "error" | within 1h
  • Searches for logs containing “error” within the last 1 hour.

Aggregation

Count Logs:

count({job="app"} |= "error")
  • Counts the number of logs containing “error” in the “app” job.
count_over_time({job="app"} |= "error" | group_left [1h])
  • Counts logs containing “error” over time with a 1-hour step.

Regular Expressions

Regex Matching:

{job="app"} |~ "error|warn"
  • Searches for logs containing either “error” or “warn.”

Labels and Context

Include Labels in Output:

{job="app"} | logfmt | json
  • Includes labels in the output by converting logs to JSON.

Sorting

Sort Logs:

{job="app"} | sort_desc | head 10
  • Sorts logs in descending order and displays the first 10.

Field Selection

Select Specific Fields:

{job="app"} | json | fields app, level
  • Selects only the “app” and “level” fields from logs.

Advanced Queries

Complex Queries:

sum_over_time({job="app"} |= "error" | group_left [1h]) > 10
  • Calculates the sum of logs containing “error” over time and checks if it’s greater than 10.

Regexp Filtering

Regex Filter by Labels:

{job="app", level=~"error|warn"}
  • Filters logs with the “job” label set to “app” and “level” label matching “error” or “warn.”

This cheat sheet covers some of the basic and more advanced LogQL queries. For more detailed information and examples, refer to the official Loki documentation.