Resources
1 min read
Loki, a log aggregation system from Grafana, uses LogQL (Loki Query Language) to query logs. Whether you're just starting or need a quick reference, this cheat sheet covers the essentials. Let's dive into the syntax and functions of LogQL to make your log querying efficient and effective.
Contents
Basics of LogQL
LogQL has two main components:
- Log Streams Selector: Defines which log streams to include in the query.
- Filter Expressions: Refine the data within the selected log streams.
Log Stream Selector
The log stream selector is a set of key-value pairs that define which log streams you want to query. Here's the basic format:
{label1="value1", label2="value2"}
Examples:
{job="varlogs"} {app="nginx", environment="production"}
Filter Expressions
Filter expressions allow you to search within the log streams. They can be used with or without log stream selectors.
|= (equals): Exact match != (not equals): Exclude exact matches |~ (regex): Regex match !~ (not regex): Exclude regex matches
Examples:
{job="varlogs"} |= "error" {app="nginx"} |~ "status=5.."
Advanced Queries
Aggregation Operators
Aggregation operators allow you to perform calculations on your log data.
count_over_time: Counts log entries over a specified time range. rate: Calculates the rate of log entries per second.
Functions
LogQL includes several functions to process and analyze log data:
sum: Sums up values. avg: Calculates the average value.
Operators
Operators are used to combine multiple expressions:
and / or: Logical AND / OR. |: Pipeline operator for chaining filters.
Practical Examples
Here are some practical examples to illustrate the use of LogQL in real-world scenarios:
Count Errors in Nginx Logs: {app="nginx"} |= "error"
Average Rate of 5xx Responses: avg(rate({app="nginx"} |~ "status=5.." [1m]))
Sum of Log Entries for a Specific Job: sum(count_over_time({job="varlogs"}[10m]))
Filtering and Parsing JSON Logs: {app="json_app"} |= "error" | json
This cheat sheet covers the essential LogQL queries and functions to help you get the most out of Loki. Keep this guide handy for quick reference and to enhance your log querying skills. Have we missed something? Feel free to email [email protected] with your suggestions or questions.
If you enjoyed this sheet then why not check out Kubectl cheat sheet or our Linux commands cheat sheet next?