RousselTMLEARNING

Observability

Alerting on logs with the Loki Ruler

Set up LogQL alerts and recording rules with the Loki Ruler: configuration, rule files, Alertmanager, remote write and testing.

1. Principle #

The same mechanism as Prometheus, with LogQL.

Alerts and recording rules #

The Ruler runs metric-type LogQL queries at an interval. An alert notifies Alertmanager when the result exceeds a threshold for the for duration; a recording rule precomputes a series and writes it through remote write.

How the Loki Ruler works
The Ruler reads rules from disk or from object storage.

2. Configuring the Ruler #

Rule storage and destinations.

loki.yaml #

ruler:
  storage:
    type: local
    local:
      directory: /loki/rules              # <répertoire>/<tenant>/*.yaml
  rule_path: /loki/rules-temp
  alertmanager_url: http://alertmanager:9093
  ring: { kvstore: { store: inmemory } }
  enable_api: true
  enable_alertmanager_v2: true
  remote_write:
    enabled: true
    client:
      url: http://prometheus:9090/api/v1/write
Good to know: With auth_enabled: false, the tenant is called fake: put the rules in /loki/rules/fake/rules.yaml.

3. Writing rules #

Alerts and recordings.

Rule file #

# /loki/rules/fake/rules.yaml
groups:
  - name: logs-alerts
    interval: 1m
    rules:
      - alert: HighErrorLogRate
        expr: sum by (app) (rate({env="prod"} |= "error" [5m])) > 5
        for: 10m
        labels: { severity: warning }
        annotations:
          summary: "Taux d'erreurs élevé dans {{ $labels.app }}"
          description: "{{ $value | printf \"%.1f\" }} erreurs/s depuis 10 minutes."

      - alert: ServiceSilent
        expr: absent_over_time({app="payment", env="prod"}[10m])
        for: 5m
        labels: { severity: critical }
        annotations: { summary: "Plus aucun log reçu du service payment" }

  - name: logs-recording
    rules:
      - record: app:log_errors:rate5m
        expr: sum by (app) (rate({env="prod"} |= "error" [5m]))

4. Testing and operating #

API and checks.

The Ruler API #

curl -s http://localhost:3100/prometheus/api/v1/rules | jq '.data.groups[].rules[] | {name, state}'
curl -s http://localhost:3100/prometheus/api/v1/alerts | jq
curl -s http://localhost:3100/loki/api/v1/rules             # règles stockées

# Charger des règles avec lokitool / cortex-tools
lokitool rules sync --address=http://localhost:3100 --id=fake rules.yaml
lokitool rules check rules.yaml
lokitool rules lint rules.yaml
Good practice: Test the expression in Explore first: a query that returns data and a realistic threshold avoid noisy alerts.

5. Managing rules through the API #

Adding, updating, reading and deleting rules without touching files.

The endpoints #

The Ruler exposes a configuration API compatible with Cortex and Mimir. Rules are organized by tenant (X-Scope-OrgID header), then by namespace (a free name, for example a team or an application), then by group.

Method and pathEffect
GET /loki/api/v1/rulesall of the tenant's rules (YAML)
GET /loki/api/v1/rules/{namespace}a namespace's groups
GET /loki/api/v1/rules/{namespace}/{groupe}one group
POST /loki/api/v1/rules/{namespace}creates or replaces a group (YAML body); returns 202 Accepted
DELETE /loki/api/v1/rules/{namespace}/{groupe}deletes one group
DELETE /loki/api/v1/rules/{namespace}deletes the whole namespace
GET /prometheus/api/v1/rules, /alertsstate of evaluated rules and active alerts (JSON, read only)

Prerequisite: writable storage #

# loki.yaml: writable rule storage (here S3 / MinIO)
ruler:
  enable_api: true                     # enables the /loki/api/v1/rules endpoints
  storage:
    type: s3
    s3:
      endpoint: minio:9000
      bucketnames: loki-ruler
      access_key_id: ${S3_ACCESS_KEY}
      secret_access_key: ${S3_SECRET_KEY}
      s3forcepathstyle: true
      insecure: true
  rule_path: /loki/rules-temp
  alertmanager_url: http://alertmanager:9093
Watch out : The local storage of the previous example is read-only for the API: POST and DELETE requests fail. To manage rules through the API, use object storage (S3, MinIO, GCS, Azure, Swift…), shared by every Ruler instance.
Good to know : With auth_enabled: true, every call must carry the tenant X-Scope-OrgID header; behind a gateway (nginx, Grafana Cloud), also add the expected authentication (basic or token).

Adding a rule #

The POST body is a single group in YAML: name, optional interval and the rules list, without the groups: wrapper used in files. Sending a group that already exists replaces it entirely.

# api-errors.yaml: ONE rule group (no “groups:” key for the API)
name: api-errors
interval: 1m
rules:
  - alert: ApiErrorBurst
    expr: sum by (app) (rate({namespace="prod", app="api"} |= "level=error" [5m])) > 2
    for: 10m
    labels:
      severity: critical
    annotations:
      summary: "More than 2 errors/s for {{ $labels.app }}"
  - record: app:log_errors:rate5m
    expr: sum by (app) (rate({namespace="prod"} |= "level=error" [5m]))
LOKI=http://localhost:3100
TENANT=fake                            # X-Scope-OrgID value (“fake” if auth_enabled: false)

# Create or replace the “api-errors” group in the “prod” namespace
curl -s -X POST "$LOKI/loki/api/v1/rules/prod" \
  -H "X-Scope-OrgID: $TENANT" -H "Content-Type: application/yaml" \
  --data-binary @api-errors.yaml -w '%{http_code}\n'            # 202 = accepted

# Read: all rules, one namespace, one group (YAML responses)
curl -s -H "X-Scope-OrgID: $TENANT" "$LOKI/loki/api/v1/rules"
curl -s -H "X-Scope-OrgID: $TENANT" "$LOKI/loki/api/v1/rules/prod"
curl -s -H "X-Scope-OrgID: $TENANT" "$LOKI/loki/api/v1/rules/prod/api-errors"

# Check that the Ruler evaluates it (Prometheus view, JSON)
curl -s -H "X-Scope-OrgID: $TENANT" "$LOKI/prometheus/api/v1/rules" | jq '.data.groups[] | {name, rules: [.rules[].name]}'

# Delete one group, then the whole namespace
curl -s -X DELETE -H "X-Scope-OrgID: $TENANT" "$LOKI/loki/api/v1/rules/prod/api-errors"
curl -s -X DELETE -H "X-Scope-OrgID: $TENANT" "$LOKI/loki/api/v1/rules/prod"

Automating in a pipeline #

Version rules in Git (one file per group, one folder per namespace), validate them with lokitool rules lint, then publish them. Two options: lokitool rules sync, which creates, updates and deletes to align the Ruler with the files, or the API directly, as below, when you only want to add or replace.

# Option 1: full sync (also deletes groups missing from files)
lokitool rules sync --address=$LOKI --id=$TENANT rules/*/*.yaml
lokitool rules diff --address=$LOKI --id=$TENANT rules/*/*.yaml     # see differences first

# Option 2: API, file by file (files in lokitool's “groups:” format)
for f in rules/*/*.yaml; do
  ns=$(basename "$(dirname "$f")")
  yq '.groups[0]' "$f" | curl -sf -X POST "$LOKI/loki/api/v1/rules/$ns" \
    -H "X-Scope-OrgID: $TENANT" -H 'Content-Type: application/yaml' --data-binary @- \
    && echo "OK $ns/$(yq '.groups[0].name' "$f")"
done

Common errors #

SymptomLikely cause
404 on /loki/api/v1/rulesenable_api missing, or calling a component that does not run the Ruler
Error on POST while reading workslocal storage (read-only)
401 or “no org id”X-Scope-OrgID header missing with auth_enabled: true
400 on POSTinvalid YAML, groups: wrapper sent, or wrong LogQL expression
Rule accepted but missing from /prometheus/api/v1/rulesthe Ruler loads it on the next cycle (sync interval, one minute by default): wait
Best practice : Rules managed through the API live in object storage: keep Git as the source of truth and republish from CI, rather than editing them by hand with curl in production.

Related articles

The LGTM stack (Loki, Grafana, Tempo, Mimir): architecture and setup

Grafana Labs' LGTM stack: Loki for logs, Grafana for visualization, Tempo for traces, Mimir for metrics (and …

Grafana Loki: the Prometheus-inspired log system

Discover Grafana Loki: the label-indexing philosophy, architecture (distributor, ingester, querier, compactor…

Installing Grafana Loki (Docker Compose, binary and Helm)

Install and validate Grafana Loki: minimal configuration, Docker Compose with Grafana and Alloy, binary insta…

Keep learning

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!