Grafana sits as the single pane of glass over both halves of this lesson: Prometheus metrics via provisioned dashboards, and Loki logs via Explore. Credentials in this lab really are admin / admin; grab the URL from make urls.

needsmake up obs

Orientation

competency 4.1 · logging and actionable dashboards

The blueprint asks for "dashboards that provide actionable insight": that's a design judgment, not a UI click-through. Two habits make it real: shipping dashboards as versioned code, and building every panel around a specific question an on-call engineer actually asks.

Dashboards as code

the sidecar pattern

In a kube-prometheus-stack cluster, dashboards are provisioned from Git, never hand-clicked in the UI. A sidecar container inside the Grafana pod watches for ConfigMaps labeled grafana_dashboard: "1" and hot-loads every dashboard JSON inside them. That's how the stack ships 40+ dashboards out of the box, and how your platform ships team dashboards through GitOps. Datasources follow the exact same pattern using grafana_datasource: "1".

git ──▶ ConfigMap (label grafana_dashboard=1) ──▶ sidecar writes /tmp/dashboards ──▶ Grafana loads it
                                                                                     │
   a dashboard clicked together in the UI lives only in Grafana's database           │
   and dies with the pod ────────────────────────────────────────────────────────────┘

What makes a dashboard genuinely actionable

  • Lead with user-visible symptoms. Use RED for services (Rate, Errors, Duration), USE for infrastructure resources (Utilization, Saturation, Errors), or the four golden signals (latency, traffic, errors, saturation). Know all three frameworks cold and which workload each fits.
  • Use template variables ($namespace, $pod) driven by label_values() queries instead of hardcoding names, so one dashboard serves every tenant.
  • Earn every panel. If a panel doesn't answer an incident question, cut it. A 40-panel wall of noise slows diagnosis down.
  • Connect signals with annotations and links. Deployment markers immediately answer "did this start after a rollout?", and panel links straight into Loki Explore turn a spike into a root cause in one click.

Quick tour of Grafana's pieces: datasources (Prometheus and Alertmanager come pre-wired here; you'll wire up Loki and Jaeger in the exercises), panels with clean units and thresholds, Grafana alerting (intentionally skipped in our lab since Prometheus rules are the exam focus), and folders + permissions for multi-team orgs.

Loki and LogQL

index labels, not content

Loki takes a deliberately lean design: it indexes labels, not full log text. Lines are grouped into streams by a compact label set (namespace, pod, container, app), and text filtering scans only the matching streams at query time. That keeps storage cheap, requires every query to start with a stream selector, and makes label discipline critical, since slapping a request ID into a label would explode streams immediately.

In our lab, Alloy runs in monitoring, tailing pod logs via the kubelet API and shipping them to the Loki StatefulSet next door. That's two moving parts, which is why make validate queries Loki for actual streams rather than just checking pod readiness, because a healthy Loki with a broken shipper stays silently empty.

LogQL pieceExampleDoes
stream selector{namespace="team-a"}mandatory first step; picks log streams
line filter|= "error" · != "/healthz" · |~ "5[0-9]{2}"fast substring or regex match before parsing
parser| json · | logfmt · | patternextracts structured fields into temporary labels
label filter| status >= 500filters on parsed fields
metric querysum by (pod) (rate({namespace="x"} |= "error" [5m]))turns log streams into alertable time series

Master those five building blocks and you can handle almost any exam log prompt. Pay special attention to the fifth one: metric queries over logs let you alert on failures that only ever show up in text logs.

Often the terminal beats the UI

Use stern <pattern> -n <ns> to tail multiple pods live with color-coded prefixes, and kubectl logs --previous to catch a crashed container's dying output. Reach for Loki when asking "what happened an hour ago across the fleet?", and reach for stern / kubectl when asking "what is happening right this second?"

Picking the right signal fast

Metrics answer "how much / how often?" cheaply across long windows. Logs answer "what exact error did this pod print?" Traces (4.4) answer "which hop in the call chain slowed down or broke?" Picking the right signal on the first try saves precious minutes under exam pressure.

Provisioning, field by field

datasource and dashboard files, sidecar knobs, the Grafana Operator

Grafana's native provisioning files

Files under provisioning/datasources/*.yaml and provisioning/dashboards/*.yaml begin with apiVersion: 1. A datasource specifies name, type (prometheus, loki, jaeger, tempo), url, access: proxy, a stable uid (set this explicitly so exported dashboards never break on import), isDefault, editable: false to block UI drift, plus jsonData (httpMethod: POST, timeInterval, Loki's derivedFields linking trace IDs to Jaeger/Tempo, alertmanagerUid) and secureJsonData for encrypted credentials. Use deleteDatasources to replace entries cleanly by name. Dashboard provider files set folder, type: file, options.path, foldersFromFilesStructure, allowUiUpdates (default false), and disableDeletion.

In kube-prometheus-stack, the sidecar handles this plumbing automatically: ConfigMaps labeled grafana_dashboard: "1" load into the General folder (a grafana_folder: <name> annotation only routes them into folders if sidecar.dashboards.folderAnnotation is enabled in chart values; our lab leaves it off), and ConfigMaps/Secrets labeled grafana_datasource: "1" register datasources. Because the sidecar watches all namespaces by default, any team's Helm chart can ship its own dashboards automatically.

The Grafana Operator (when an exam hands you CRDs)

Kind (grafana.integreatly.org/v1beta1)HoldsField to watch
Grafanaa Grafana instance (managed or external via spec.external.url)its labels are what every other CRD targets via instanceSelector
GrafanaDashboarda dashboard from json, gzipJson, url, configMapRef, jsonnet, or grafanaCom.idinstanceSelector, folder/folderRef, resyncPeriod, and datasources[] to bind ${DS_PROMETHEUS} inputs
GrafanaDatasourcedatasource spec (datasource.jsonData, secureJsonData, valuesFrom for Secret refs)instanceSelector; requires allowCrossNamespaceImport: true on the Grafana CR for cross-namespace imports
GrafanaFoldera folder with optional parentFolderRef and permissionsreferenced by dashboards via folderRef
GrafanaAlertRuleGroup / GrafanaContactPoint / GrafanaNotificationPolicy / GrafanaMuteTimingGrafana-managed alerting as codesecondary when Prometheus rules are in use, though worth recognizing by name

Same familiar trap here too: a GrafanaDashboard whose instanceSelector.matchLabels matches no Grafana CR applies cleanly and silently does nothing. Whenever exporting dashboard JSON for GitOps, leave "export for sharing externally" turned off so datasource UIDs stay literal, keep id: null with a stable uid, and use label_values(kube_pod_info, namespace) variables.

Loki internals and deeper LogQL

components, labels vs structured metadata, parsers, shippers, retention

Architecture and deployment modes

Writes flow from the distributor (validates and hashes streams onto the ring) to the ingester (batches chunks in memory before flushing to object storage) with quorum acks. Reads flow through query-frontend → query-scheduler → querier (pulling fresh lines from ingesters and older chunks from object storage). Supporting roles: compactor (merges TSDB indexes and enforces retention), ruler (evaluates LogQL alerting/recording rules), and index gateway (serves index lookups). Everything persists to one object store (S3, GCS, Azure, MinIO). You'll see three deployment topologies: single binary (-target=all), simple scalable (read, write, backend), and full microservices. When a scalable Loki returns empty results, suspect the write path first.

Labels vs. structured metadata

Every distinct label combination spawns a stream with its own chunks and index entries (capped by max_streams_per_user and 15 labels per stream by default). Keep index labels low-cardinality and steady: namespace, app, container, and level. High-cardinality fields you still want fast filtering on (trace ID, request ID, even ephemeral pod names) belong in structured metadata, stored per line inside chunks and queryable with identical filter syntax without creating streams. Loki's OTLP ingest (/otlp/v1/logs) automatically routes core resource attributes (service.name, k8s.namespace.name) to index labels and the rest to structured metadata.

LogQL constructs beyond the basics

ConstructExampleNote
| pattern| pattern "<ip> - - <_> \"<method> <path> <_>\" <status>"blazing-fast extraction for fixed formats; <_> skips fields
| regexp| regexp "(?P<user>\\w+) logged in"named capture groups become labels; slowest option
| json a="b.c"extract specific JSON paths onlybare | json flattens every field and can blow label limits on big payloads
| line_format / | label_format| line_format "{{.method}} {{.status}}"Go templates to reshape lines mid-pipeline
| __error__=""filter out unparseable linesfailed parses stay in the output tagged with __error__ unless dropped
| unwrap durationquantile_over_time(0.95, {app="api"} | logfmt | unwrap duration [5m]) by (path)converts an extracted number into numeric samples (duration_seconds(x) and bytes(x) handle units)
count_over_time / bytes_rate / absent_over_timeabsent_over_time({job="backup"} |= "completed" [25h])clean pattern for alerting when a scheduled job stays silent
offsetcount_over_time({app="x"}[5m] offset 1w)placed inside the range expression, unlike PromQL
| drop / | keep| keep status, pathtrim clutter before aggregating

Two syntax details that save real debugging time: stream-selector regexes are fully anchored, while line-filter regexes (|~) are not; and range brackets must sit right after the log pipeline (rate({a="b"} |= "x" [5m]) works, while rate({a="b"}[5m] |= "x") won't parse).

Log shippers, retention, and rules

  • Promtail is EOL (LTS ended Feb 2026, full EOL March 2, 2026). Grafana Alloy replaces it with composable blocks (discovery.kubernetes → loki.source.kubernetes or loki.source.file → loki.process → loki.write), and alloy convert --source-format=promtail migrates legacy configs automatically. You may also encounter the OpenTelemetry Collector (filelog receiver → otlp_http exporter to Loki's /otlp) or Fluent Bit; all three typically run as DaemonSets tailing /var/log/pods.
  • Retention requires the compactor: enable compactor.retention_enabled: true alongside limits_config.retention_period (or per-stream retention_stream rules). Leave the compactor flag off and Loki keeps chunks forever regardless of the retention period.
  • Ruler: evaluates Prometheus-style rule groups written in LogQL, sends firing alerts to ruler.alertmanager_url, and can remote_write log-derived recording rules straight into Prometheus.
How this gets tested

"Find which pod logged X in the past hour" → stream selector + |=. "Count errors per service over time" → sum by (app) (count_over_time(... |= "error" [5m])). "Compute p95 latency from access logs" → logfmt or pattern + unwrap + quantile_over_time. Spot which of the three patterns a prompt is asking for and you're already halfway done.

Exercises

tick the dot when its check passes

In Grafana: Connections → Data sources. If Loki is not there, add it the provisioned way rather than the UI way:

kubectl -n monitoring apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: loki-datasource
  labels: { grafana_datasource: "1" }
data:
  loki.yaml: |
    apiVersion: 1
    datasources:
      - name: Loki
        type: loki
        url: http://loki.monitoring.svc:3100
        access: proxy
EOF
outputcaptured 2026-08-26
$ kubectl -n monitoring apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: loki-datasource
  labels: { grafana_datasource: "1" }
data:
  loki.yaml: |
    apiVersion: 1
    datasources:
      - name: Loki
        type: loki
        url: http://loki.monitoring.svc:3100
        access: proxy
EOF
configmap/loki-datasource created

The sidecar picks it up within a minute or so. If nothing arrives, bisect the two hops: shipper first (kubectl -n monitoring get deploy alloy, then its logs for push errors), Loki second.

verify: Explore → Loki → {namespace="monitoring"} returns log lines. If nothing returns, name which hop is broken.

Generate known lines, then find them (team-a comes from make sec; kubectl apply -f examples/multitenancy/team-a.yaml creates it standalone):

kubectl -n team-a run chatty --image=busybox:1.37 --restart=Never -- \
  sh -c 'for i in $(seq 60); do echo "level=error msg=payment_failed attempt=$i"; sleep 1; done'
outputcaptured 2026-08-26
$ kubectl -n team-a run chatty --image=busybox:1.37 --restart=Never -- \
  sh -c 'for i in $(seq 60); do echo "level=error msg=payment_failed attempt=$i"; sleep 1; done'
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "chatty" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "chatty" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "chatty" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "chatty" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/chatty created

In Explore: {namespace="team-a"} |= "payment_failed", then the metric form sum(rate({namespace="team-a"} |= "payment_failed" [1m])).

verify: lines visible and the rate curve is about 1/s while the pod runs. Compare stern chatty -n team-a for the same lines live.

Build one panel in the UI first (New dashboard → add visualization → Prometheus → sum by (namespace) (rate(container_cpu_usage_seconds_total[5m]))), then export its JSON (share → Export → save JSON, set "export for sharing externally" off), and re-deliver it properly:

kubectl -n monitoring create configmap team-cpu-dashboard --from-file=dash.json=<your-file> \
  --dry-run=client -o yaml | kubectl label -f - --local --dry-run=client -o yaml grafana_dashboard=1 | kubectl apply -f -
outputcaptured 2026-08-26
$ kubectl -n monitoring create configmap team-cpu-dashboard --from-file=dash.json=dash.json \
  --dry-run=client -o yaml | kubectl label -f - --local --dry-run=client -o yaml grafana_dashboard=1 | kubectl apply -f -
configmap/team-cpu-dashboard created
verify: delete the hand-made dashboard in the UI, and the provisioned copy appears (default folder) and survives a Grafana pod delete, which the clicked one would not have. State the GitOps moral in one sentence.

Open "Kubernetes / Compute Resources / Namespace (Pods)" for team-a while the chatty pod runs. Answer: which panels are RED, which are USE, and which single panel would you keep if you could keep one during a pod-crash incident.

verify: there is no single right answer; having an answer with a reason is the skill the "actionable insights" wording points at.

A derived field turns a trace id in a log line into a link to the trace. It is a regex and a datasource uid in a provisioning file, and it is what joins the two halves of an investigation without a copy and paste.

# port 3000 on this host is Backstage, not Grafana: a curl there returns HTML and jq says 'Invalid numeric literal'
# and the derived field needs a Jaeger datasource with the uid it points at
kubectl -n monitoring delete cm loki-datasource --ignore-not-found
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: jaeger-datasource
  namespace: monitoring
  labels: { grafana_datasource: "1" }
data:
  jaeger.yaml: |
    apiVersion: 1
    datasources:
      - name: Jaeger
        type: jaeger
        uid: jaeger-lab
        access: proxy
        url: http://jaeger.tracing.svc:16686
EOF
kubectl -n monitoring get cm -l grafana_datasource=1 -o name
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: loki-datasource-linked
  namespace: monitoring
  labels: { grafana_datasource: "1" }
data:
  loki-linked.yaml: |
    apiVersion: 1
    # the Loki added earlier on this page has the same name and a generated uid: replace it
    deleteDatasources:
      - { name: Loki, orgId: 1 }
    datasources:
      - name: Loki
        type: loki
        uid: loki-lab
        access: proxy
        url: http://loki.monitoring.svc:3100
        editable: false
        jsonData:
          derivedFields:
            - name: TraceID
              matcherRegex: "trace_id=(\\w+)"
              url: "$${__value.raw}"
              datasourceUid: jaeger-lab
EOF
kubectl -n monitoring wait --for=condition=available deploy/prometheus-grafana --timeout=180s
sleep 45
GF_PW=$(kubectl -n monitoring get secret prometheus-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
kubectl -n monitoring port-forward --address 127.0.0.1 svc/prometheus-grafana 3300:80 & PF1=$!
sleep 5
curl -s -u admin:admin 127.0.0.1:3300/api/datasources | jq '[.[] | {name, uid, type}]'
curl -s -u admin:admin 127.0.0.1:3300/api/datasources/uid/loki-lab | jq '.jsonData'
kill $PF1
kubectl -n monitoring delete cm jaeger-datasource
kubectl -n monitoring delete cm loki-datasource-linked --ignore-not-found
outputcaptured 2026-11-18
$ # port 3000 on this host is Backstage, not Grafana: a curl there returns HTML and jq says 'Invalid numeric literal'
$ # and the derived field needs a Jaeger datasource with the uid it points at
$ kubectl -n monitoring delete cm loki-datasource --ignore-not-found
configmap "loki-datasource" deleted from monitoring namespace
$ kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: jaeger-datasource
  namespace: monitoring
  labels: { grafana_datasource: "1" }
data:
  jaeger.yaml: |
    apiVersion: 1
    datasources:
      - name: Jaeger
        type: jaeger
        uid: jaeger-lab
        access: proxy
        url: http://jaeger.tracing.svc:16686
EOF
configmap/jaeger-datasource created
$ kubectl -n monitoring get cm -l grafana_datasource=1 -o name
configmap/jaeger-datasource
configmap/prometheus-kube-prometheus-grafana-datasource
$ kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: loki-datasource-linked
  namespace: monitoring
  labels: { grafana_datasource: "1" }
data:
  loki-linked.yaml: |
    apiVersion: 1
    # the Loki added earlier on this page has the same name and a generated uid: replace it
    deleteDatasources:
      - { name: Loki, orgId: 1 }
    datasources:
      - name: Loki
        type: loki
        uid: loki-lab
        access: proxy
        url: http://loki.monitoring.svc:3100
        editable: false
        jsonData:
          derivedFields:
            - name: TraceID
              matcherRegex: "trace_id=(\\w+)"
              url: "$${__value.raw}"
              datasourceUid: jaeger-lab
EOF
configmap/loki-datasource-linked created
$ kubectl -n monitoring wait --for=condition=available deploy/prometheus-grafana --timeout=180s
deployment.apps/prometheus-grafana condition met
$ sleep 45
$ GF_PW=$(kubectl -n monitoring get secret prometheus-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
$ kubectl -n monitoring port-forward --address 127.0.0.1 svc/prometheus-grafana 3300:80 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:3300 -> 3000
$ curl -s -u admin:admin 127.0.0.1:3300/api/datasources | jq '[.[] | {name, uid, type}]'
Handling connection for 3300
[
  {
    "name": "Alertmanager",
    "uid": "alertmanager",
    "type": "alertmanager"
  },
  {
    "name": "Jaeger",
    "uid": "jaeger-lab",
    "type": "jaeger"
  },
  {
    "name": "Loki",
    "uid": "loki-lab",
    "type": "loki"
  },
  {
    "name": "Prometheus",
    "uid": "prometheus",
    "type": "prometheus"
  }
]
$ curl -s -u admin:admin 127.0.0.1:3300/api/datasources/uid/loki-lab | jq '.jsonData'
Handling connection for 3300
{
  "derivedFields": [
    {
      "datasourceUid": "jaeger-lab",
      "matcherRegex": "trace_id=(\\w+)",
      "name": "TraceID",
      "url": "${__value.raw}"
    }
  ]
}
$ kill $PF1
$ kubectl -n monitoring delete cm jaeger-datasource
configmap "jaeger-datasource" deleted from monitoring namespace
$ kubectl -n monitoring delete cm loki-datasource-linked --ignore-not-found
configmap "loki-datasource-linked" deleted from monitoring namespace
verify: the datasource exists with the uid you chose and its jsonData carries the derived field. Open a log line in Explore and the TraceID appears as a link; if the link is dead, the target uid is wrong, not the regex.

A dashboard ConfigMap lands in the General folder unless you say otherwise, and General is where dashboards go to be lost. One annotation fixes it, and it is the difference between a dashboard people find and one they rebuild.

kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: platform-overview
  namespace: monitoring
  labels: { grafana_dashboard: "1" }
  annotations: { grafana_folder: "Platform" }
data:
  platform-overview.json: |
    {
      "title": "Platform overview",
      "uid": "platform-overview",
      "schemaVersion": 39,
      "panels": [
        {"type": "timeseries", "title": "API server requests", "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
         "targets": [{"expr": "sum(rate(apiserver_request_total[5m]))"}]}
      ]
    }
EOF
sleep 60
# port 3000 here is Backstage; Grafana answers on 3300
GF_PW=$(kubectl -n monitoring get secret prometheus-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
kubectl -n monitoring port-forward --address 127.0.0.1 svc/prometheus-grafana 3300:80 & PF1=$!
sleep 5
curl -s -u admin:admin 127.0.0.1:3300/api/search?query=Platform%20overview | jq '.[] | {title, folderTitle, uid}'
# the sidecar only honours the annotation when it is told which one to read
kubectl -n monitoring get deploy prometheus-grafana -o jsonpath='{range .spec.template.spec.containers[?(@.name=="grafana-sc-dashboard")].env[*]}{.name}={.value}{"\n"}{end}' | grep -i -E 'folder|provider'
kill $PF1
kubectl -n monitoring delete cm platform-overview
outputcaptured 2026-09-13
$ kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: platform-overview
  namespace: monitoring
  labels: { grafana_dashboard: "1" }
  annotations: { grafana_folder: "Platform" }
data:
  platform-overview.json: |
    {
      "title": "Platform overview",
      "uid": "platform-overview",
      "schemaVersion": 39,
      "panels": [
        {"type": "timeseries", "title": "API server requests", "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
         "targets": [{"expr": "sum(rate(apiserver_request_total[5m]))"}]}
      ]
    }
EOF
configmap/platform-overview created
$ sleep 60
$ # port 3000 here is Backstage; Grafana answers on 3300
$ GF_PW=$(kubectl -n monitoring get secret prometheus-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
$ kubectl -n monitoring port-forward --address 127.0.0.1 svc/prometheus-grafana 3300:80 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:3300 -> 3000
$ curl -s -u admin:admin 127.0.0.1:3300/api/search?query=Platform%20overview | jq '.[] | {title, folderTitle, uid}'
Handling connection for 3300
{
  "title": "Platform overview",
  "folderTitle": null,
  "uid": "platform-overview"
}
$ # the sidecar only honours the annotation when it is told which one to read
$ kubectl -n monitoring get deploy prometheus-grafana -o jsonpath='{range .spec.template.spec.containers[?(@.name=="grafana-sc-dashboard")].env[*]}{.name}={.value}{"\n"}{end}' | grep -i -E 'folder|provider'
FOLDER=/tmp/dashboards
$ kill $PF1
$ kubectl -n monitoring delete cm platform-overview
configmap "platform-overview" deleted from monitoring namespace
verify: the dashboard is imported and /api/search finds it by title, but folderTitle is null: it landed at the top level, not in Platform. The annotation is not wrong, it is unread. The sidecar's environment carries only FOLDER=/tmp/dashboards and no FOLDER_ANNOTATION, so no annotation on any ConfigMap can place a dashboard in a folder on this install. Set sidecar.dashboards.folderAnnotation and sidecar.dashboards.provider.foldersFromFilesStructure in the chart values and the same ConfigMap lands in Platform. A convention that depends on a setting nobody enabled is the most common way dashboards end up in one flat list.

LogQL beyond a plain filter is where the marks are: parse a line into fields, turn a field into a number, notice an absence, and find the lines your parser could not handle.

kubectl -n monitoring port-forward svc/loki 3100:3100 & PF1=$!
sleep 5
curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query={namespace="team-a"} | pattern `<ip> - - <_> "<method> <uri> <_>" <status> <size>`' --data-urlencode 'limit=5' | jq '.data.result[0].values[0]'
curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query=quantile_over_time(0.95, {namespace="team-a"} | pattern `<_> <_> <_> <_> "<_> <_> <_>" <status> <size> ` | unwrap size [5m]) by (status)' | jq '.data.result'
curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query=absent_over_time({namespace="default", pod="does-not-exist"}[5m])' | jq '.data.result'
curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query={namespace="team-a"} | logfmt --strict | __error__ != ""' --data-urlencode 'limit=5' | jq '.data.result[0].stream'
kill $PF1
outputcaptured 2026-09-13
$ kubectl -n monitoring port-forward svc/loki 3100:3100 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:3100 -> 3100
Forwarding from [::1]:3100 -> 3100
$ curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query={namespace="team-a"} | pattern `<ip> - - <_> "<method> <uri> <_>" <status> <size>`' --data-urlencode 'limit=5' | jq '.data.result[0].values[0]'
Handling connection for 3100
[
  "1789307349067886028",
  "10.244.2.200 - - [13/Sep/2026:13:49:09 +0000] \"GET / HTTP/1.1\" 200 615 \"-\" \"kube-probe/1.36\" \"-\"\n"
]
$ curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query=quantile_over_time(0.95, {namespace="team-a"} | pattern `<_> <_> <_> <_> "<_> <_> <_>" <status> <size> ` | unwrap size [5m]) by (status)' | jq '.data.result'
Handling connection for 3100
[
  {
    "metric": {
      "status": "200"
    },
    "values": [
      [
        1789303754,
        "615"
      ],
      [
        1789303768,
        "615"
      ],
      [
        1789303782,
        "615"
      ],
      [
        1789303796,
        "615"
      ],
      [
        1789303810,
        "615"
      ],
      [
        1789303824,
        "615"
      ],
      [
        1789303838,
        "615"
      ],
      [
        1789303852,
        "615"
      ],
      [
... 1002 more lines
$ curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query=absent_over_time({namespace="default", pod="does-not-exist"}[5m])' | jq '.data.result'
Handling connection for 3100
[
  {
    "metric": {
      "namespace": "default",
      "pod": "does-not-exist"
    },
    "values": [
      [
        1789303754,
        "1"
      ],
      [
        1789303768,
        "1"
      ],
      [
        1789303782,
        "1"
      ],
      [
        1789303796,
        "1"
      ],
      [
        1789303810,
        "1"
      ],
      [
        1789303824,
        "1"
      ],
      [
        1789303838,
        "1"
      ],
      [
        1789303852,
        "1"
      ],
... 1003 more lines
$ curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query={namespace="team-a"} | logfmt --strict | __error__ != ""' --data-urlencode 'limit=5' | jq '.data.result[0].stream'
Handling connection for 3100
{
  "__error__": "LogfmtParserErr",
  "__error_details__": "logfmt syntax error at pos 47 : unexpected '\"'",
  "app": "demo",
  "container": "web",
  "detected_level": "unknown",
  "instance": "team-a/staging-demo-66955f8974-l48bx:web",
  "job": "loki.source.kubernetes.pods",
  "namespace": "team-a",
  "pod": "staging-demo-66955f8974-l48bx",
  "service_name": "demo"
}
$ kill $PF1
verify: the pattern parser produces labeled fields, unwrap turns size into a number you can take a quantile of, absent_over_time returns a series for the pod that does not exist, and logfmt --strict plus __error__ != "" returns the nginx access lines, which are not logfmt at all. The --strict flag is the point: plain logfmt in Loki 3 skips what it cannot parse and sets no __error__, so the same query without it comes back empty and you conclude, wrongly, that every line parsed.

Alloy replaced promtail, and every migration task is the same: take the old config, run the converter, read what it produced. The command lives in the Alloy image.

cat > /tmp/promtail.yaml <<'EOF'
server:
  http_listen_port: 9080
clients:
  - url: http://loki.monitoring.svc:3100/loki/api/v1/push
scrape_configs:
  - job_name: kubernetes-pods
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      - source_labels: [__meta_kubernetes_namespace]
        target_label: namespace
EOF
POD=$(kubectl -n monitoring get pod -l app.kubernetes.io/name=alloy -o jsonpath='{.items[0].metadata.name}')
kubectl -n monitoring cp /tmp/promtail.yaml "$POD":/tmp/promtail.yaml
kubectl -n monitoring exec "$POD" -- alloy convert --source-format=promtail /tmp/promtail.yaml
outputcaptured 2026-09-13
$ cat > /tmp/promtail.yaml <<'EOF'
server:
  http_listen_port: 9080
clients:
  - url: http://loki.monitoring.svc:3100/loki/api/v1/push
scrape_configs:
  - job_name: kubernetes-pods
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      - source_labels: [__meta_kubernetes_namespace]
        target_label: namespace
EOF
$ POD=$(kubectl -n monitoring get pod -l app.kubernetes.io/name=alloy -o jsonpath='{.items[0].metadata.name}')
$ kubectl -n monitoring cp /tmp/promtail.yaml "$POD":/tmp/promtail.yaml
$ kubectl -n monitoring exec "$POD" -- alloy convert --source-format=promtail /tmp/promtail.yaml
discovery.kubernetes "kubernetes_pods" {
	role = "pod"

	selectors {
		role  = "pod"
		field = "spec.nodeName=" + coalesce(sys.env("HOSTNAME"), constants.hostname)
	}
}

discovery.relabel "kubernetes_pods" {
	targets = discovery.kubernetes.kubernetes_pods.targets

	rule {
		source_labels = ["__meta_kubernetes_namespace"]
		target_label  = "namespace"
	}
}

loki.source.file "kubernetes_pods" {
	targets    = discovery.relabel.kubernetes_pods.output
	forward_to = [loki.write.default.receiver]

	file_match {
		enabled = true
	}
	legacy_positions_file = "/var/log/positions.yaml"
}

loki.write "default" {
	endpoint {
		url = "http://loki.monitoring.svc:3100/loki/api/v1/push"
	}
	external_labels = {}
}
verify: the converter prints Alloy components: a discovery block, a relabel block, a source block and a write block, wired by references.

Retention in Loki is a compactor setting, and it is off by default in more distributions than people expect. Read it before you promise a week of logs to an audit.

kubectl -n monitoring get cm loki -o yaml | grep -A6 -E 'compactor|retention'
kubectl -n monitoring get cm loki -o jsonpath='{.data.config\.yaml}' | grep -E 'retention_enabled|retention_period|delete_request' || echo 'no retention keys in the rendered config'
kubectl -n monitoring get pvc -l app.kubernetes.io/name=loki
outputcaptured 2026-09-12
$ kubectl -n monitoring get cm loki -o yaml | grep -A6 -E 'compactor|retention'
      compactor_grpc_address: 'loki.monitoring.svc.cluster.local:9095'
      path_prefix: /var/loki
      replication_factor: 1
      storage:
        filesystem:
          chunks_directory: /var/loki/chunks
          rules_directory: /var/loki/rules
$ kubectl -n monitoring get cm loki -o jsonpath='{.data.config\.yaml}' | grep -E 'retention_enabled|retention_period|delete_request' || echo 'no retention keys in the rendered config'
no retention keys in the rendered config
$ kubectl -n monitoring get pvc -l app.kubernetes.io/name=loki
NAME             STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
storage-loki-0   Bound    pvc-4589502f-0ed6-4923-9993-473e891d6ebf   10Gi       RWO            standard       <unset>                 123m
verify: you can say whether retention_enabled is set on this install and what would delete old chunks if it is not. "The disk fills up" is a legitimate answer, and it is the one that matters for capacity planning.

Self-check

answer before opening
How does a dashboard get into Grafana in a GitOps platform, and why not click it?

Ship the dashboard JSON inside a ConfigMap labeled grafana_dashboard: "1" from Git, and let Grafana's sidecar load it. Dashboards clicked together in the UI live only inside Grafana's database: unreviewed, unversioned, and wiped out on pod restarts without persistent storage.

Explain RED and USE, and which you would use for a queue worker.

RED (Rate, Errors, Duration) fits request-driven services; USE (Utilization, Saturation, Errors) fits hardware and pools. A queue worker benefits from both plus queue depth: USE for worker pool capacity, RED-like metrics for message processing, and backlog growth as your saturation signal.

Loki returns nothing for {namespace="team-a"}. Two hops to check, in order.

Check the shipper first (is Alloy running, tailing that namespace, and pushing without errors?), then Loki (is the ingester healthy, is retention dropping the window, and are multi-tenant org headers right?). A healthy Loki with a broken shipper stays quietly empty.

Why is a per-request-ID label a bad idea in Loki?

Every unique label set spawns a new stream and index entry. A per-request label creates millions of tiny streams, thrashing memory and slowing queries. Keep high-cardinality IDs in the log body (or structured metadata) and filter them at query time.

Turn "alert me when payments start failing" into a LogQL-based rule, conceptually.

Write a LogQL metric query such as sum(rate({namespace="payments"} |= "payment_failed" [5m])) > 0.1 and evaluate it in Loki's ruler (or remote-write it into Prometheus via a recording rule). From there, Alertmanager routes it just like any Prometheus alert.

A dashboard imported from a ConfigMap shows "datasource not found" on every panel. What did the export get wrong, and what is the durable fix?

It was exported with "export for sharing externally" enabled (turning datasources into unbound ${DS_PROMETHEUS} variables) or references a random UID that doesn't exist in this cluster. Fix it by provisioning datasources with explicit stable uids and exporting with external sharing off, or mapping datasources[] in a Grafana Operator GrafanaDashboard.

Why is a trace ID a bad Loki label but a good candidate for structured metadata, and how do you still search it quickly?

As an index label, every unique trace ID mints a separate stream and blows up Loki's index. As structured metadata, key-value pairs ride inside the chunks without spawning streams while staying fast to filter using regular label syntax (| trace_id="abc"). Alloy and OTLP ingest route high-cardinality attributes there automatically.

Your shipper is a Promtail DaemonSet from an older tutorial. Why is that a problem in 2026, and what replaces it?

Promtail hit end-of-life on March 2, 2026 with no further security or bug fixes. Migrate to Grafana Alloy (alloy convert --source-format=promtail handles the config translation), or use vendor-neutral shippers like the OpenTelemetry Collector (filelog receiver) or Fluent Bit.

Docs to know your way around

study time, not exam time
  • grafana.com/docs: provisioning (datasources and dashboards), dashboard variables, and the LogQL reference.
  • The Explore UI's query builder doubles as LogQL documentation under time pressure.
  • Offline: stern --help, kubectl logs --previous, and the Grafana panel inspector (it shows the exact query and the raw response).
  • grafana.com/docs/grafana/latest/administration/provisioning: datasource and dashboard provider file formats (uid, jsonData, secureJsonData, foldersFromFilesStructure); grafana.github.io/grafana-operator/docs/api for the CRD fields.
  • grafana.com/docs/loki/latest/query/log_queries and /query/metric_queries: parsers, __error__, unwrap; /get-started/labels for the structured-metadata guidance.
  • grafana.com/docs/alloy/latest/set-up/migrate/from-promtail: the EOL statement and the component mapping.