Looking at Logs with, Loki
local graph
Chapter 4 — Looking at Logs with, Loki
Section titled “Chapter 4 — Looking at Logs with, Loki”In this chapter, we will get hands-on experience with Grafana Loki. We will learn how to use LogQL, which is the language used for querying Loki, how to select and filter log streams, and how to use the operators and aggregations available. This will give you the tools to extract the data in appropriate ways for your dashboard visualizations and alerts. We will review the benefits and drawbacks of the log format and how it impacts your use of Loki. To fully explore the benefits of Loki, we will explore the architecture and where it can be scaled for performance. To finish, we will look at advanced areas of LogQL, such as labels and transformations, and other tips and tricks to expand your use of Loki.
We will cover the following main topics in this chapter:
- Introducing Loki
- Understanding LogQL
- Exploring Loki’s architecture
- Tips, tricks, and best practices
Technical requirements
Section titled “Technical requirements”In this chapter, you will work with LogQL using the Grafana Cloud instance and demo you set up in Chapter 3. The full LogQL language documentation can be found on the Grafana website at https://grafana.com/docs/loki/latest/logql/. Loki is in active development, so it’s worth checking for new features frequently.
You’ll find the code for this chapter in the GitHub repository at https://github.com/PacktPublishing/Observability-with-Grafana/tree/main/chapter4. You’ll find the Code in Action videos for this chapter at
Updating the OpenTelemetry demo application
Section titled “Updating the OpenTelemetry demo application”First, let’s improve the logging for our demo application. For this chapter, we have provided an updated OTEL-Collector.yaml file with additional Loki log labels in the chapter4 folder in the GitHub repository. These instructions assume you have already completed the demo project setup in Chapter 3. Full details on this process are available in the GitHub repository in the Chapter 4 section of the README.md file.
To upgrade the OpenTelemetry Collector, follow these steps:
- Upgrade the collector
$ helm upgrade --version '0.73.1' --values chapter4/OTEL-Collector.yaml --values OTEL-Creds.yaml owg open-telemetry/opentelemetry-collectorNAME: owg-otel-collectorLAST DEPLOYED: Sun Apr 25 12:15:03 2023NAMESPACE: defaultSTATUS: deployedREVISION: 2…
- You can validate that the upgrade was successful with
$ kubectl get pods --selector=app.kubernetes.io/instance=owgNAME READY STATUS RESTARTS AGEowg-opentelemetry-collector-594fddd656-tfstk 1/1 Terminating 1 (70s ago) 2m8sowg-opentelemetry-collector-7955d689c4-gsvqm 1/1 Running 0 3s
You will now have a lot more labels available for your Loki log data. Let’s explore what that means in the next section.
Introducing Loki
Section titled “Introducing Loki”Grafana Loki was designed from the ground up to be a highly scalable multi-tenant logging solution. Its design was heavily influenced by Prometheus with a few main objectives:
- It was built with developers and operators in mind (such as Diego and Ophelia, who were introduced in Chapter 1)
- It has simple ingestion; no pre-parsing is required
- It only indexes metadata about logs
- It stores everything in an object store
Let’s look at how Loki ingests data and uses labels as this will provide valuable insight into the way your queries source and then process the data for presentation:
- Log ingest: Loki accepts logs from all sources with a wide choice of agents available to make that easy. You can even send log data directly to the Loki API. This makes it the perfect choice for complex environments featuring a multitude of systems and hardware components.
Loki stores its logs as log streams, where each entry has the following:
- Timestamp: It has nanosecond precision for accuracy.
- Labels: These are key-value pairs used for the identification and retrieval of your data; they form the Loki index.
- Content: This refers to the raw log line. It is not indexed and is stored in compressed chunks.
The following diagram shows a log stream with a log line and its associated metadata:

- Timestamp: It has nanosecond precision for accuracy.
Figure 4.1 – Loki log structure
- Log labels: Loki log labels provide the metadata for the log line and not only help identify the data but also are used to create the index for the log streams and structure the log storage. They have the following features:
- Each unique set of labels and values creates a log stream
- Logs in a stream are batched, compressed, and stored as chunks
- Labels are the index to Loki’s log streams
- Labels are used to search for logs
- Each unique set of labels and values creates a log stream
The following diagram demonstrates two log streams. As you can see, in a stream of logs, each log has the same unique set of labels. In this instance, k8s_node_name has two values:

Figure 4.2 – Loki log streams
Now that we have looked at the structure of a Loki log, let’s introduce LogQL, the query language used to extract value from your logs.
Understanding LogQL
Section titled “Understanding LogQL”Grafana developed LogQL as the query language for Loki using the Prometheus Query Language (PromQL) for inspiration. It was designed with developers (Diego) and operators (Ophelia) in mind (you can refer to Chapter 1 for an introduction to these personas), providing familiar filtering and aggregation mechanisms. Loki does not index the log content. Log events are grouped into log streams and indexed with labels (the log metadata). Executing a LogQL query in Loki invokes a type of distributed filtering against log streams to aggregate the log data.
Let’s explore the Grafana explorer UI for LogQL, where you will be executing most of your LogQL queries.
LogQL query builder
Section titled “LogQL query builder”We took a brief look at the Grafana explorer UI in Figure 3*.16* in Chapter 3. For our examples, we will mostly work with raw LogQL in the Code editor. The following screenshot shows LogQL typed directly into the query builder code editor:

Figure 4.3 – LogQL query builder Code editor
If you ever get stuck with your LogQL, you can lean on the Log query starters and Explain query tools to help you get started with your queries and understand what each step of your pipeline is doing.
Log query starters provides some quick examples to work with your data and get you filtering and formatting it with ease:

Figure 4.4 – Log query starters
Similarly, Metric query starters provides some quick examples to work with your data and generate metrics ready for use in dashboards and alerts:

Figure 4.5 – Metric query starters
Available in the LogQL query builder and the dashboard panel editor, Explain query, when toggled on, provides a breakdown of each stage of your LogQL pipeline. This tool is invaluable when analyzing an existing query or debugging your own during design:

Figure 4.6 – Explain query
Let’s now explore the features of LogQL available for selecting, filtering, and parsing your log data.
An overview of LogQL features
Section titled “An overview of LogQL features”A basic LogQL query consists of one or more log stream selectors to retrieve the raw log chunks for processing and an optional log pipeline to filter and parse the log data. The following figure shows a basic LogQL query with the component="cartservice" selector and a pipeline filter, |= `GetCartAsync`, which would return two lines from the log stream example in Figure 4*.2*:

Figure 4.7 – A basic LogQL query
The following reference table shows the different features available to you when building your LogQL query, which will help while you get familiar with querying your logs with Loki:
| LogQL Sections | Syntax | Operators | Scope |
|---|---|---|---|
| Stream selector | { label="value", foo!="bar"} | =, !=, =~, !~ | Select log streams to retrieve; there must always be at least one selector |
| Line filter | |= ` error` | |=, !=, |~, !~ | Filter to matching log lines |
| Parser | | json | json, logfmt, pattern, regexp, unpack | Parse and extract labels from the log content, with parses for structured and unstructured logs |
| Label filter | | label="value" | =, !=, =~, !~, <, <=, >, >= | Filter log lines using original and newly extracted labels |
| Line format | | line_format "{{.label}}" | Rewrite the log line content for presentation purposes | |
| Label format | | new_label="{{.label}}" | Rename, modify, or add labels |
Table 4.1 – LogQL feature overview
Let’s start by looking at the log stream selector in detail.
Log stream selector
Section titled “Log stream selector”Selecting log streams to include in your query results requires filtering based on the Loki labels using simple operators. By improving the granularity of your log stream selector, you can reduce the number of streams searched and improve query performance. We will discuss this in more detail later in this chapter when we look at the Loki architecture. There must always be at least one stream selector, but it must be written in a way that will not match empty values; for example, the regular expression (regex) {label=~".*"} will fail as a 0 or more quantifier and {label=~".+"} will pass as a 1 or more quantifier. Multiple stream selectors can be used and are separated using commas. The log stream selector must be the first item in your LogQL query and identified with curly braces. For example, the following LogQL query will select log streams where the component label ends with service and the name label equals owg-demo-checkoutservice:
{component=~".+service", name="owg-demo-checkoutservice"}As mentioned at the beginning of this section, LogQL was inspired by PromQL and as such, the Prometheus label selector rules have been adopted by LogQL for log stream selectors:
| Operator | Meaning |
|---|---|
| = | Exactly equal |
| != | Not equal |
| =~ | Regex matches |
| !~ | Regex does not match |
Table 4.2 – Log stream selector operators
Grafana has implemented the Golang RE2 syntax for log streams, which means you will have to match against entire strings. This includes newlines, so it’s worth checking this if your regex filters are failing. Syntax documentation can be found here: https://github.com/google/re2/wiki/Syntax.
Once you have your log streams selected, the log pipeline can then be used to filter and process them. Let’s discuss this next.
Log pipeline
Section titled “Log pipeline”As we presented in Table 4.1, the expressions available are line and label filters, parsers, and formatters. Expressions are executed in sequence for each line of the log stream, dropping anything filtered out and moving on to the next line.
Expressions allow you to transform or mutate the log data to then use it for additional filtering/processing. Let’s look at the following example (this is the pipeline section only; you would need the {component=~".+service"} selector to make it work in Grafana):
|= \`emailservice\`| json| resources_k8s_container_restart_count > 0| line_format \`{{.body}}\`| __error__=\`\`Here, we’re doing the following tasks:
- We start by matching the logs containing
emailservice. - We then use the
jsonparser to extract additional labels that are filtered whereresources_k8s_container_restart_countis greater than 0. - We then rewrite the log line to only contain the contents of
body. - Finally, we strip all formatting and parsing errors.
Let’s now look at each of the log pipeline expressions and how to use them.
Line filters
Section titled “Line filters”Grafana describes line filters as a distributed grep over the aggregated logs from the matching log streams. We will understand this statement better in the Loki’s architecture section. For now, it’s fine to just understand line filters as case-sensitive searches through log line contents dropping lines that do not match. Filter expressions are made up of a filter operator followed by text or regex. The following table shows the meaning of each expression with examples:
| Operator | Meaning | Example |
|---|---|---|
|= | Log line contains a string | |= ` emailservice` |
!= | Log line does not contain a string | != ` emailservice` |
|~ | Log line contains a match to the regex | |~ ` email\w+` |
!~ | Log line does not contain a match to the regex | !~ ` email\w+` |
Table 4.3 – Line filters
It is best practice to start log pipelines with line filter expressions to reduce the result set for subsequent expressions and improve the performance of the query.
IP address matching
Section titled “IP address matching”LogQL provides a useful function to aid IP address matching without complex regex patterns. Using the ip("<pattern>") syntax, it supports both IPv4 and IPv6 addresses, address ranges, and CIDR patterns. This function works for both line and label filters with a slight caveat in implementation; only |= and != are allowed for line filter expressions. We’ll look at this in the context of label filters later in this section.
The following examples show various patterns (ip(<pattern>)) along with an explanation of what each will do, for both IPv4 and IPv6:
- Match a single IP address:
ip("192.168.0.22")andip("::1") - Find a match within a range:
ip("192.168.0.1-192.189.10.12")andip("2001:db8::1-2001:db8::8") - Find a match within a CIDR specification:
ip("192.52.100.0/24")andip("2001:db8::/32")
Decolorize
Section titled “Decolorize”In Chapter 2, we mentioned unstructured logging is often color-coded to improve readability on the computer terminal. However, in a log aggregation system, such as Loki, those color codes are displayed in full. For example, the color red would be displayed as \u001b31m.
Loki has a simple line filter expression that removes these ANSI sequences for color codes so that you can clean the log to make it more readable in Grafana:
{name="emailservice"} | decolorizeParsers
Section titled “Parsers”We have said this before: Loki accepts logs from all sources. It does not really matter what your logs look like; they can come in structured, semi-structured, or unstructured formats. It is, however, important when designing and building observability solutions to understand the log formats you are working with. This ensures that you can ingest, store, and parse log data in a way it can be used effectively. The personas in [Chapter 1 give you an idea of who these will be used by and for what purpose.
Having a good understanding of your source log format is important to instruct you on what to use and help with your overall observability design. The following LogQL parsers can be used to parse and extract labels from your log content:
json: If your log content is structured or semi-structured JSON and has embedded JSON (which can be isolated using theline_formatexpression), the JSON parser can be used. Using| jsonon its own will extract all of the JSON properties as labels. Any nested properties will be represented as a single label separated with_. Arrays are skipped completely when extracting all of the properties. Additionally, expressions can be passed into the JSON parser as quoted strings to restrict the output to only the labels required, for example,| json label1="expression", label2="expression", where the expression identifies a key or nested key. Arrays are returned where identified by expressions and they are assigned to the label formatted as JSON.logfmt: If your log content is structured, single-level key-value pairs, it can be parsed with the logfmt parser. Using| logfmton its own will extract all of the key-value pairs. Similar to the JSON parser, expressions can be passed into thelogfmtparser as quoted strings to restrict the output to only the labels required, for example,| logfmt label1="expression", label2="expression", whereexpressionidentifies a key.pattern: For unstructured log content, the pattern parser allows the explicit extraction of fields from log lines using| pattern "<expression>", whereexpressionmatches the structure of a log line. The pattern parser expression is made up of captures delimited by the<and>characters and literals, which can be any sequence of UTF-8 characters.regexp: Unstructured log content can also be extracted using the regular expression parser, which takes a single expression,| regexp "<expression>", whereexpressionis a regex pattern that complies with the Golang RE2 syntax. A valid expression must contain at least one sub-match, with each sub-match extracting a different label.unpack: If you are using a compatible logging agent, such as Grafana Agent or Promtail, you can take advantage of theunpackparser to unpack embedded labels created by Promtail’spackfeature. With Promtail’spackfeature, the original log line is stored in the_entrykey. This value will be used to replace the log line.
Label filters
Section titled “Label filters”We discussed log labels at the beginning of this section with regard to log ingestion and retrieval. Additionally, labels can be extracted as part of the log pipeline using parser and formatter expressions. The label filter expression can then be used to filter your log line with either of these labels.
The statement part of the filter is referred to as the predicate, and in the case of label filters, it contains the following:
- The label identifier
- The operation
- A value
For example, in name="emailservice", the name label is compared, using the = operator, with the value "emailservice". It is processed from left to right, so the label identifier must start the predicate.
Value types are inferred from your query input. In the following table, you will find an overview of these types as a useful reference for building your label filters:
| Value Type | Description |
|---|---|
| String | Can be surrounded with double quotes or backticks, for example, "emailservice" or `emailservice`. |
| Duration | Structured as a sequence of decimal numbers. They can optionally contain fractions and the unit can be declared as a suffix, for example, "280ms", "1.3h", or "2h30m". Units of time that can be used are "ns", "us" (or "µs"), "ms", "s", "m", and "h", and as the examples show, you can use multiple units: "2h30m". |
| Number | Standard floating-point numbers, for example, 357 or 98.421. |
| Bytes | Structured as a sequence of decimal numbers. They can optionally contain fractions and the unit can be declared as a suffix, for example, "36MB", "2.4Kib", or "18b". Units for bytes that can be used are "b", "kib", "kb", "mib", "mb", "gib", "gb", "tib", "tb", "pib", "pb", "eib", and "eb". |
Table 4.4 – Value types
Let’s now look at these value types in more detail:
- String: As with the label matchers we use with the log stream selector, the
=,!=,=~, and!~operations can be used. Thestringtype is used to filter the built in label__error__, which is often used to strip formatting and parsing errors from results; for example,|__error__=``. - Duration, Number, and Bytes: All of the remaining value types follow the same rules. Duration, Number, and Bytes convert the label value for use with the following list of comparators:
Operator Meaning =or==Equals !=Does not equal >and>=Is greater than or greater than and equal to <and<=Is less than or less than and equal to
Table 4.5 – Type operators
Take the example | resources_k8s_container_restart_count > 0. Loki attempts to convert the value for use with the operator if it needs to. If there are any errors with the conversion, the __error__ label will be added to the log line, which as we demonstrated earlier, can be filtered out using | __error__=``.
Grafana LogQL also allows for multiple predicates to be chained together using and and or. and can alternatively be expressed using , or | or <space>.
For example, all of the following produce the same output:
| quantity >= 2 and productId!~"OLJ.*"| quantity >= 2 | productId!~"OLJ.*"| quantity >= 2 , productId!~"OLJ.*"| quantity >= 2 productId!~"OLJ.*"We described IP address matching in the Line filters section. Label filter expressions are the same except only the = and != label matchers are allowed. Once you have filtered and parsed your logs as required, you can begin to transform the data, whether that is for presentation or further pipeline processing. We will discuss the two ways of doing this in detail next. But first, let’s explore template functions, which are implemented by both line and label filters.
Template functions
Section titled “Template functions”The Golang text/template format has a large set of available template functions, all of which are available for use in LogQL queries. Full documentation can be found on the Grafana website. The templating engine has access to your data in various ways:
- It can treat labels as variables, referencing them using
., for example,{{ .``component }} - It can access the log line itself using
__line__, for example,`{{ __line__ |lower }}` - It can access the log timestamp using
__timestamp__, for example,`{{ __timestamp__ | date "2023-04-25T12:15:03.00Z+01:00" }}`
Template functions can be broken down into the following distinct areas:
- Regex patterns
- String functions
- Math functions
- JSON functions
- Date and time functions
In addition, there are other functions that do not necessarily fit into a grouping but are nevertheless very useful. These include encode and decode functions, byte and duration conversions, counts, and default values.
Line and label format
Section titled “Line and label format”Two features are available for transforming logs:
- Line format: The line format expression, given by
| line_format "{{ .label }}", is used to rewrite log line content. This expression is used to modify your log line using the template functions referenced earlier. LogQL injects all labels as variables into the template, making them available for use, for example,| line_format "{{.label_one}} {{.label_two}}". The format takes double quotes or backticks, where backticks allow you to avoid escaping characters. For example, if we have the following labels,method=sent,status=200, andduration=15ms, the following LogQL query would returnsent200 15ms:{instance="owg-demo", component="featureflagservice"} |= \`Sent\`| json| regexp "(?P<method>Sent) (?P<status>\\d+?) in\\s(?P<duration>.*?ms)"| line_format "{{.method}} {{.status}} {{.duration}}" - Label format: The label format expression given by
|label_format new_label="{{ .label }}"is used to rename, modify, or even create new labels. It accepts a comma-separated list of equality operations, allowing multiple operations to be carried out simultaneously. To rename a label with another label, the label identifiers must be on both sides of the operator; for example,target=sourcewill put the contents of thesourcelabel into thetargetlabel and drop thesourcelabel. A label can be populated using the Golang text/template format and functions detailed previously (double quotes or backticks). For example, if we have theuser=diegoandstatus=200labels, the|label_format target="{{.status}} {{.user}}"pipeline would define thetargetlabel as200 diego. Templating can be used if you wish to preserve the originalsourcelabel. In the example,target=sourceremoved thesourcelabel. We can write this astarget="{{.source}}", which will put the contents of thesourcelabel into thetargetlabel while preserving thesourcelabel. If the target label does not already exist, a new label is created.
Important note
Only one instance of a label name can be used per expression; for example, | label_format foo=bar,foo="new" would fail. The desired result could be implemented with two expressions, one following the other, like this: | label_format foo=bar | label_format foo="new".
We’ve looked at how the label format gives you options to create, modify, and rename labels. Additionally, we have the drop labels command to remove labels completely. Let’s explore that expression now.
Dropping labels
Section titled “Dropping labels”The drop labels expression is used to remove labels from the pipeline. For example, if we have the user=diego, status=200, and duration=1000(ms) labels, the |drop user pipeline would drop the user label, leaving only status and duration.
We will now take a look at more of the LogQL features, exploring formatters, metric queries, and the UI for executing LogQL the Grafana Explorer where queries for all data sources are built.
Exploring LogQL metric queries
Section titled “Exploring LogQL metric queries”One of the most powerful features of Loki and LogQL is the ability to create metrics from logs. With metric queries, you can, for example, calculate the rate of errors or the top 10 log sources with the highest volume of logs over the last hour. This makes it perfect for creating visualizations or triggering alerts.
If we combine metric queries with the parsers and formatters we looked at earlier in this section, they can be used to calculate metrics from sample data within a log line. For example, latency or request size can be extracted from log data and used as a metric. These will then be available for aggregations and the generation of new series.
Let’s now take a look at the aggregations available, namely, range vector aggregations and built-in aggregation operators.
Range vector aggregations
Section titled “Range vector aggregations”The Prometheus concept of a range vector is shared by LogQL, where the range of samples is a range of log or label values. We will discuss the range vector concept in greater detail in Chapter 5. The selected aggregation is applied to a time interval specified as a number followed by a unit. The following time interval units can be used:
ms: Millisecondss: Secondsm: Minutesh: Hoursd: Daysw: Weeksy: Years
Examples are 6h, 1h30m, 10m, and 20s.
There are two types of range vector aggregations supported by Loki and LogQL: log range aggregations and unwrapped range aggregations. Let’s explore these in detail.
Log range aggregation
Section titled “Log range aggregation”A log range aggregation is a LogQL query followed by a duration, for example, [10ms], with a function applied to it to aggregate the query over the duration. The duration can be placed after the log stream selector or at the end of the log pipeline.
Here are the aggregation functions:
| Aggregation | Description |
|---|---|
rate(range) | Will calculate the number of entries per second. |
count_over_time(range) | Will count the entries for each log stream within the given range. |
bytes_rate(range) | Useful to detect changes in log data volume. It will calculate the number of bytes per second for each log stream. |
bytes_over_time(range) | Useful to calculate the volume of log data. It will count the amount of bytes used by each log stream for the given range. |
absent_over_time(range) | Useful for alerting when there are no time series and logs streams for label combinations for a duration of time. It returns an empty vector if the range passed to it has elements and a single element vector with the value 1 if the range passed to it has no elements. |
Table 4.6 – Log range aggregation functions
Here are a few log range aggregation examples:
- To count all the log lines within the last 10 minutes for the
currencyservicecount_over_time({component="currencyservice"}[10m]) - To sum the rate per second of errors by component within the
sum by (component) (rate({component=~".+service"}|= "error" [1m]))
Unwrapped range aggregations
Section titled “Unwrapped range aggregations”Unwrapped range aggregations use the LogQL unwrap function to extract a value to be used in the aggregation. They support grouping using the by or without clause to aggregate over distinct labels. The without aggregation removes the labels identified from the result vector while preserving all other labels. The by aggregation drops labels that are not identified in the by clause.
Here are the aggregation functions:
| Aggregation | Description |
|---|---|
rate(unwrapped-range) | Will calculate the per-second rate of the sum of all of the values within the interval. |
rate_counter( unwrapped-range) | Will calculate the per-second rate of all the values within the interval, treating them as counter metrics. |
sum_over_time( unwrapped-range) | Will sum of all the values within the interval. |
avg_over_time( unwrapped-range) | Will return the average of all the points within the interval. |
max_over_time(range) | Will return the maximum of all the points within the interval. |
min_over_time( unwrapped-range) | Will return the minimum of all the points within the interval. |
first_over_time( unwrapped-range): | Will return the first value of all the points within the interval. |
last_over_time( unwrapped-range) | Will return the last value of all the points within the interval. |
stdvar_over_time( unwrapped-range) | Will return the population standard variance of the values within the interval. |
stddev_over_time( unwrapped-range) | Will return the population standard deviation of the values within the interval. |
quantile_over_time(scalar, unwrapped-range) | Will return the specified quantile of the values within the interval. |
absent_over_time( unwrapped-range) | Useful for alerting when there are no time series and logs streams for label combinations for a duration of time. It returns an empty vector if the range passed to it has elements and a single element vector with the value 1 if the range passed to it has no elements. |
Table 4.7 – Unwrapped range aggregation functions
The sum_over_time, absent_over_time, rate, and rate_counter functions are excluded from grouping.
Here are a few unwrapped range aggregation examples:
- To calculate the 99th percentile of the
webservercontainerrequest_timeexcluding any JSON formatting errors bypathwithin thequantile_over_time(0.99,{container="webserver"}| json| __error__ = ""| unwrap duration_seconds(request_time) [1m]) by (path) - To calculate the number of bytes processed by
org_idwithin the last minute, filtering where the log contains themetricssum by (org_id) (sum_over_time({container="webserver"}|= "metrics"| logfmt| unwrap bytes(bytes_processed) [1m]))
Built-in aggregation operators
Section titled “Built-in aggregation operators”LogQL supports a subset of the built-in aggregation operators that PromQL supports. These can be used to aggregate the element of a single vector, resulting in a new vector of fewer elements but with aggregated values.
The following table shows some built-in range aggregation operators:
| Aggregation | Description |
|---|---|
sum | Will calculate the sum by the labels specified |
avg | Will calculate the average by the labels specified |
min | Will select the minimum by the labels specified |
max | Will select the maximum by the labels specified |
stddev | Will calculate the population standard deviation by the labels specified |
stdvar | Will calculate the population standard variance by the labels specified |
count | Will count the number of elements in a vector |
topk | Will select the largest k elements by sample value |
bottomk | Will select the smallest k elements by sample value |
sort | Will return the vector elements sorted by their sample values, in ascending order |
sort_desc | Will return the vector elements sorted by their sample values, in descending order |
Table 4.8 – Built-in range aggregation functions
Here are a few built-in range aggregation operator examples:
- To return the top 10 applications by the highest log throughput for the last 10 minutes
nametopk(10, sum(rate({region="us-west1"}[10m])) by (name)) - To return the average rate of
GETrequests to the/helloendpoint for web server logs by region for the lastavg(rate(({container="webserver"} |= "GET" | json | path="/hello")[10s])) by (region)
We have looked at how LogQL can parse different log formats. Let’s now take a look at the Loki architecture and how Loki stores and queries the log data you send.
Exploring Loki’s architecture
Section titled “Exploring Loki’s architecture”Grafana Loki has a full microservices architecture that can be run as a single binary and a simple scalable deployment to a full microservices deployment running all the components as distinct processes. At a high level, it is made up of features that implement write, read, and store functionality, as shown in the following diagram:

Figure 4.8 – High-level overview of Loki architecture
Both write and read functionality can be scaled independently to suit your particular needs and use cases.
Under the hood, Loki has the following core components:
- Distributor
- Ingester
- Query frontend
- Querier
- Backend services:
- Ruler
- Compactor
- Query scheduler
- Ruler
Let’s now look at the functionality and core components in more detail:
- Writes: Writes for the incoming log data hit the distributor, which is responsible for data sharding and partitioning, and sending them to the ingesters. The distributor validates each set of streams, checking labels, timestamps, and log line sizes, then batches log stream chunks to multiple ingesters. The ingester writes to the write-ahead logs (WALs) for resiliency and finally into the object storage backend. Both the querier and ruler read the ingester to access the most recent data. The querier can additionally access the object storage data.
- Reads: The query frontend is responsible for accelerating query execution, distributing large queries across multiple queriers and ensuring retries in the event of failure. Queriers parse the LogQL and query the underlying systems: the ingester for the most recent data and object storage for older data. The querier de-duplicates data with the same nanosecond timestamp, labels, and log content.
- Storage: The object storage is where the batched logs are stored. The compactor is responsible for maintaining the data. It monitors the object storage, de-duplicating data and removing old logs.
- Backend services: The ruler evaluates queries and performs actions based on the result. The actions can be recording rules (generating new metrics for LogQL queries) or alerts for system events. The alert manager is responsible for notifications and alerts triggering and being sent from the system, but this is not included with Loki.
- Loki index: In this chapter, so far, we have covered Loki log labels and LogQL log stream selectors. The underlying architecture completes the picture, explaining how the distributor shards the data. It is that sharding and subsequent storage using the label-based Loki index that makes Loki fast and inexpensive. It also validates the importance of a good labeling strategy to improving storage and retrieval, and essentially querying performance.
Now that we have built up a good understanding of Loki, let’s look at a few best practices and some tips for working with Loki log data.
Tips, tricks, and best practices
Section titled “Tips, tricks, and best practices”In this section, we will look at a few best practices for filtering and cardinality. We will then look at the LogQL Analyzer and LogCLI, which are tools that can help you when you are working with Grafana Loki log data.
Here are some best practices to keep in mind:
- Filter first: Loki stores the raw log in object storage as compressed chunks. Because of this, it is important, from a speed point of view, to filter early. Processing complex parsing on smaller datasets will increase the response time.
- Cardinality: High cardinality in Loki can be very detrimental. It is important to design your Loki labels well. Anything that has a lot of variable data in it is a bad idea as that will multiply the number of log streams and therefore storage chunks by that factor. Thinking of them as a locator rather than a content descriptor helps. You can always extract labels from log lines with the range of parsers available. Some examples of good labels (targeted with limited values) are the following:
namespaceclusterjobappinstancefilenameSome examples of poor labels (often vague with unlimited values) are the following:
useridtraceidpathstatus codedate
Now, let’s take a closer look at the advantages offered by using the LogQL Analyzer and LogCLI:
- LogQL Analyzer: The LogQL Analyzer provides an interface on the Grafana website for you to practice your LogQL queries. You can view detailed explanations of the actions implemented by your query on a sample log entry. Head over to https://grafana.com/docs/loki/latest/query/analyzer/ to try it out. Let’s take a look at the Loki LogQL Analyzer:

Figure 4.9 – Loki LogQL Analyzer
The explanations provided by the LogQL Analyzer are far more detailed than the Explain query feature in the query builder, so it’s worth checking out while you are learning LogQL.
- Using LogCLI: For command-line lovers everywhere, Grafana Loki comes with a command-line interface called LogCLI that allows you to do the following at your terminal:
- Query your logs
- Evaluate metric queries for a single point in time
- Identify Loki labels and obtain stats about their values
- Return log streams for a time window with a label matcher
- Query your logs
This is great if you need access to the power of LogQL without leaving the comfort of your own console.
Full setup documentation and command references can be found here: https://grafana.com/docs/loki/latest/query/. You can download the binary from the Loki releases page on GitHub.
We will now wrap up this chapter with a reminder of what you have learned.
Summary
Section titled “Summary”In this chapter, we have taken a look at Loki, exploring the log ingest format and the importance of log labels. We then started looking at the comprehensive features of LogQL, the query language of Loki, and how we can select log streams and then filter, parse, format, and transform log lines. These techniques will be invaluable when working with Loki to build dashboards in Chapter 8. Then, we looked at the Loki architecture to get an understanding of what’s going on behind the scenes. We also explained how our data is stored and how Loki can be scaled to increase performance. Lastly, we reviewed some tips and best practices that can help you improve your experience with Loki.
In the next chapter, we’ll move on from logs to explore metrics and Prometheus, where Loki took its original inspiration from.