๐Ÿ”ง DevOps

Loki

Grafana's log aggregation system

๐Ÿ“– Detailed Explanation

Loki is a horizontally scalable log aggregation system developed by Grafana Labs. It was designed with inspiration from Prometheus, and it greatly reduces operating cost and complexity by indexing only labels rather than the log body. The slogan "Prometheus, but for logs" describes its characteristics well.

Traditional log systems (such as Elasticsearch) index all the text of the logs and provide powerful full-text search, but indexing requires a lot of resources. Loki indexes only labels (e.g., app=frontend, env=prod) and stores the log body in compressed form. It searches by reading only the necessary log chunks at query time.

LogQL is Loki's query language, and it uses syntax similar to PromQL. It selects log streams with label selectors, and filters/parses/aggregates them with pipelines. For example, `{app="api"} |= "error" | json | rate(5m)` parses the logs of the api app that contain error as JSON and then calculates the occurrence rate per 5 minutes.

The Loki stack consists of Promtail (log collection agent), Loki (log storage/query), and Grafana (visualization). In a Kubernetes environment, Promtail collects Pod logs on each node and pushes them to Loki, and dashboards and alerts are configured in Grafana. Promtail can also be replaced with Fluentd/Fluent Bit or Vector.

๐Ÿ’ป Code Example

# LogQL ์ฟผ๋ฆฌ ์˜ˆ์ œ

# ๊ธฐ๋ณธ: ๋ ˆ์ด๋ธ”๋กœ ๋กœ๊ทธ ์ŠคํŠธ๋ฆผ ์„ ํƒ
{app="order-service", env="production"}

# ๋กœ๊ทธ ๋ณธ๋ฌธ ํ•„ํ„ฐ๋ง (ํฌํ•จ)
{app="order-service"} |= "error"
{app="order-service"} |= "payment" |= "failed"

# ์ •๊ทœ์‹ ํ•„ํ„ฐ๋ง
{app="api"} |~ "user_id=(\\d+)"

# ์ œ์™ธ ํ•„ํ„ฐ
{app="api"} != "healthcheck" !~ "GET /metrics"

# JSON ๋กœ๊ทธ ํŒŒ์‹ฑ
{app="api"} | json | level="error"
{app="api"} | json | response_time > 1000

# ๋ผ์ธ ํฌ๋งท (์ถœ๋ ฅ ํ˜•์‹ ๋ณ€๊ฒฝ)
{app="api"} | json | line_format "{{.timestamp}} [{{.level}}] {{.message}}"

# ๋ฉ”ํŠธ๋ฆญ ์ฟผ๋ฆฌ - ๋ถ„๋‹น ์—๋Ÿฌ ๋กœ๊ทธ ์ˆ˜
sum(rate({app="api"} |= "error" [5m])) by (instance)

# ๋กœ๊ทธ ๋ณผ๋ฅจ ๊ณ„์‚ฐ (bytes/sec)
sum(bytes_rate({app="api"}[5m])) by (app)

# ์ง€์—ฐ์‹œ๊ฐ„ ํžˆ์Šคํ† ๊ทธ๋žจ (ํŒŒ์‹ฑ๋œ ๊ฐ’ ์‚ฌ์šฉ)
{app="api"} | json | unwrap response_time_ms | histogram_quantile(0.95)
# promtail-config.yaml - Kubernetes Pod ๋กœ๊ทธ ์ˆ˜์ง‘
server:
  http_listen_port: 9080

positions:
  filename: /tmp/positions.yaml

clients:
  - url: http://loki:3100/loki/api/v1/push

scrape_configs:
  - job_name: kubernetes-pods
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      # Pod ๋„ค์ž„์ŠคํŽ˜์ด์Šค๋ฅผ ๋ ˆ์ด๋ธ”๋กœ
      - source_labels: [__meta_kubernetes_namespace]
        target_label: namespace
      # Pod ์ด๋ฆ„
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: pod
      # ์ปจํ…Œ์ด๋„ˆ ์ด๋ฆ„
      - source_labels: [__meta_kubernetes_pod_container_name]
        target_label: container
      # app ๋ ˆ์ด๋ธ”
      - source_labels: [__meta_kubernetes_pod_label_app]
        target_label: app
    pipeline_stages:
      # JSON ๋กœ๊ทธ ํŒŒ์‹ฑ
      - json:
          expressions:
            level: level
            message: msg
      # ๋ ˆ๋ฒจ๋ณ„ ๋ ˆ์ด๋ธ” ์ถ”๊ฐ€
      - labels:
          level:

๐Ÿ—ฃ๏ธ How It's Said in Practice

SRE: "The cost of operating our ES cluster is too high. How about switching to Loki? Most of our query patterns are about label filter + grep level..."

Developer: "Isn't it a drawback that you can't do free-form full-text search like in Kibana?"

Senior: "True, but 90% of what we do is filtering by app, trace_id, and level. LogQL in Grafana Explore covers that well enough. The cost will drop to 1/5."

Interviewer: "Do you have experience building a log system?"

Candidate: "I built a Loki-based log stack. I collected Pod logs with Promtail and added app, namespace, and level to the labels. In Grafana, I connected Loki and Prometheus data sources so that metrics and logs could be viewed on the same dashboard. I set up alerts with a LogQL query to fire when the number of errors per minute exceeds a threshold."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "Watch out for label cardinality in the Promtail configuration. If you put high cardinality values like user_id into labels, Loki performance drops sharply."

Author: "Ah, I'll change it so that user_id is left in the log body instead of a label, and then parsed and filtered with LogQL."

โš ๏ธ Cautions

๐Ÿ”ฅ Real-World Incidents

SaaS Company 2023

Loki performance plummets due to high cardinality labels

Cause: user_id and request_id were added as labels, generating millions of unique label combinations

Impact: Loki index size exploded, query timeouts, and Ingester OOM occurred

Resolution: Removed high cardinality values from labels, included them only in the log body, and parsed them with LogQL

Lesson: Use only low cardinality values such as app, env, and level as labels, and keep unique identifiers in the log body

E-commerce Case 2022

Query without a time range paralyzes the entire cluster

Cause: A `{app="api"}` query was run from a Grafana dashboard without a time filter

Impact: Full scan of 90 days of logs, Querier CPU at 100%, all other queries timed out

Resolution: Forcibly terminated the query and limited the time range with the max_query_length setting

Lesson: Configure query_range limits and enforce a default time range on dashboards

๐Ÿ“ Comprehension Quiz

Q1. Why is Loki cheaper than Elasticsearch?

Q2. Which value should not be used as a label in Loki?

Q3. What does `{app="api"} |= "error" | json | rate(5m)` mean in LogQL?

๐Ÿ“š Learn More

๐Ÿ’ฌ Questions & Contributions

If this page has any errors or you would like to add something, please let us know!