Grafana Loki

Also known as: Loki

On this page 6

Grafana Loki, usually called simply Loki, is an open-source log aggregation system that collects logs from servers and applications, stores them cheaply and makes them searchable through the LogQL query language. In the area of monitoring & logs, it is known for a deliberate design choice: it indexes only metadata labels, not the full text of each log line.

Loki was created by Grafana Labs and is often described as Prometheus for logs, because it uses the same label model and the same service discovery concepts. It integrates natively with Grafana dashboards, so operators can move from a metric spike to the matching log lines in one interface.

How Loki stores and indexes logs

Loki works by grouping log lines into streams, where each stream is defined by a unique set of labels such as job, host, namespace or level. Only these labels go into a small index; the log text itself is compressed into chunks and written to inexpensive object storage.

At query time, Loki first uses the label index to select the relevant streams and time range, and then scans the chunk contents in parallel with filter expressions. This trades some query speed for a much smaller index and lower storage cost than full-text engines.

The main components of a Loki deployment are summarized below.

ComponentRoleScaling behavior
DistributorReceives and validates incoming log streamsStateless, scales horizontally
IngesterBuffers recent data and builds chunksStateful, uses replication
QuerierExecutes LogQL against index and chunksStateless, scales with query load
Query frontendSplits, queues and caches large queriesStateless
CompactorMerges index files and applies retentionUsually a single instance
Object storageHolds chunks and index long termS3-compatible or cloud bucket
Main Loki components and their roles

Small installations run all components in one binary using monolithic mode, while larger ones use simple scalable or microservices mode to scale read and write paths independently.

Collecting logs and querying with LogQL

Logs reach Loki through agents that tail files, read the systemd journal or receive container output, attach labels and push batches over HTTP. Historically the dedicated agent was Promtail; Grafana Labs now steers users toward Grafana Alloy, and Fluent Bit, Fluentd and OpenTelemetry collectors can also ship logs to Loki.

LogQL combines a stream selector in braces with a pipeline of filters, parsers and formatters. A query such as {job="nginx"} |= "error" returns matching lines, while metric queries like rate({job="nginx"} |= "error" [5m]) turn logs into time series for dashboards and alerts.

ElementExamplePurpose
Stream selector{app="api", env="prod"}Chooses streams by label
Line filter|= "timeout"Keeps lines containing text
Regex filter|~ "5[0-9]{2}"Matches a pattern
Parser| json or | logfmtExtracts fields from structured logs
Label filter| status >= 500Filters on extracted fields
Range aggregationcount_over_time(...[1h])Builds metrics from log lines
Common LogQL building blocks

The Loki ruler evaluates LogQL rules on a schedule and sends alerts to Alertmanager, so log-based conditions such as a rising error rate can trigger notifications like metric alerts.

Loki compared with other log platforms

Loki differs from the ELK stack, Graylog and Splunk mainly in what it indexes. Those platforms build inverted indexes over log content, which makes arbitrary text search fast but consumes far more storage and memory.

CriterionGrafana LokiElasticsearch-based stackSplunk
IndexingLabels onlyFull text and fieldsFull text and fields
Storage costLow, object storageHigh, index on fast disksHigh, licensed by volume
Ad hoc text searchSlower on broad rangesFastFast
Query languageLogQLKQL or Lucene syntaxSPL
VisualizationGrafanaKibanaBuilt-in interface
LicensingAGPLv3 open sourceMixed licensesCommercial
Loki compared with full-text log platforms

Loki is therefore strongest when teams already use Prometheus and Grafana, know which service they are investigating and need long retention at low cost. It is weaker for security analytics that require fast free-text searches across all data.

Label design and operational limits

The single most important practice with Loki is keeping label cardinality low. Every unique label combination creates a separate stream, and too many streams fragment chunks, inflate the index and slow ingestion.

Candidate labelSuitabilityReason
Environment or clusterGoodFew stable values
Service or job nameGoodMatches how operators search
Log levelAcceptableSmall fixed set of values
User ID or request IDPoorUnbounded values explode stream count
Client IP addressPoorHigh cardinality; filter in queries instead
Full URL pathPoorMany unique values; parse at query time
Good and poor label choices

High-cardinality values belong in the log line or in structured metadata, where queries can extract them with parsers. Operators should also set per-tenant ingestion limits, a retention period enforced by the compactor, and query limits that stop a single broad search from exhausting queriers.

  • Out-of-order or late logs may be rejected if they fall outside the accepted time window.
  • Queries over long ranges without filters read large volumes of chunks and can time out.
  • Ingester memory grows with active streams, so cardinality directly affects RAM needs.
  • Multi-tenancy requires an authenticating proxy, because Loki trusts the tenant header it receives.

Understanding it simply

Servers constantly write diaries called logs, recording every request and every error. Loki is a place where all those diaries are collected so people can read and search them together.

Instead of creating a detailed index of every word, as a library catalog would, Loki only labels each diary with a few tags, such as which program wrote it and on which server. That keeps storage cheap. When you search, Loki finds the right diaries by their tags and then reads through them quickly. The trade-off is clear: you save considerable money and space, but you need to know roughly where to look.

Applied in practice

A mid-sized software company runs about 120 containers across a Kubernetes cluster and previously kept logs in a self-managed Elasticsearch cluster that needed three large nodes with fast SSDs. Storage costs and index maintenance were growing faster than traffic.

The operations team deployed Loki in simple scalable mode, with Grafana Alloy agents on each node attaching only namespace, app, container and level labels. Chunks were written to an S3-compatible bucket with a 90-day retention period. Existing Grafana dashboards gained log panels linked to the Prometheus metrics already in use.

Daily ingestion of roughly 200 GB of logs now produces an index of only a few gigabytes, and the monthly storage bill dropped substantially. During an incident, an engineer clicks the latency spike on a dashboard, opens the matching error lines from the same five minutes, and finds a misconfigured connection pool in minutes rather than searching several tools.