TExcelTAD
Home › Kubernetes › Observability: Logs, Metrics & Events

Observability: Logs, Metrics & Events

When something goes wrong at 3 a.m., you need to see what the cluster and your apps were doing. Kubernetes observability rests on three signals, plus the cluster's own events:

Signal Built-in tool Production stack
Logs kubectl logs Fluent Bit / Vector / Promtail → Loki, Elasticsearch, CloudWatch
Metrics kubectl top (metrics-server) Prometheus + Grafana, or a cloud monitoring service
Traces – OpenTelemetry → Jaeger, Tempo
Events kubectl get events Event exporters → your log system

Logs

Containers should write logs to stdout/stderr, not to files. The container runtime stores them on the node (/var/log/pods/…), rotates them, and kubectl logs reads them through the kubelet.

bash
kubectl logs api-7d9f-x2k4p                      # one Pod
kubectl logs api-7d9f-x2k4p -c sidecar           # one container
kubectl logs -f deploy/api                       # follow (one Pod of the Deployment)
kubectl logs -l app=api --prefix --tail=20       # several Pods by label
kubectl logs api-7d9f-x2k4p --previous           # the crashed run
kubectl logs api-7d9f-x2k4p --since=10m --timestamps

Logs on the node disappear with the Pod, so production clusters run a log collector as a DaemonSet that ships every line elsewhere. Structured (JSON) logs make that searchable. A model of what a collector does: parse, enrich with Kubernetes metadata, filter:

python · try it yourself
import json

raw_lines = [
    ('api-7d9f-x2k4p', '{"level":"info","msg":"order created","order_id":1042,"ms":38}'),
    ('api-7d9f-x2k4p', '{"level":"error","msg":"payment declined","order_id":1043,"ms":412}'),
    ('api-7d9f-9qmzt', 'plain text line from an old library'),
    ('api-7d9f-9qmzt', '{"level":"warn","msg":"slow query","ms":1250}'),
]
pod_meta = {"api-7d9f-x2k4p": {"namespace": "shop", "node": "worker-1", "app": "api"},
            "api-7d9f-9qmzt": {"namespace": "shop", "node": "worker-2", "app": "api"}}

records = []
for pod, line in raw_lines:
    try:
        record = json.loads(line)
    except json.JSONDecodeError:
        record = {"level": "unknown", "msg": line}
    record["k8s"] = {"pod": pod, **pod_meta[pod]}
    records.append(record)

print("errors and warnings:")
for r in records:
    if r["level"] in ("error", "warn"):
        print(f"  [{r['level']:5}] {r['k8s']['pod']} on {r['k8s']['node']}: {r['msg']}")
slow = [r for r in records if r.get("ms", 0) > 400]
print("requests over 400 ms:", len(slow))
errors and warnings:
  [error] api-7d9f-x2k4p on worker-1: payment declined
  [warn ] api-7d9f-9qmzt on worker-2: slow query
requests over 400 ms: 2

Metrics

metrics-server collects CPU and memory usage from every kubelet; that's enough for kubectl top and the HPA:

bash
kubectl top nodes
kubectl top pods -n shop --sort-by=memory --containers

Sample output:

text
NAME          CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)
demo-worker   412m         10%      2875Mi          36%
demo-worker2  198m         4%       1904Mi          24%

For real monitoring, Prometheus scrapes /metrics endpoints (your apps, kube-state-metrics for object state, node-exporter for machines) and stores time series. The Prometheus Operator adds CRDs such as ServiceMonitor and PrometheusRule. Most alerts boil down to rates and ratios over a window. Here are two classic ones, computed from counter samples:

python · try it yourself
# requests_total counters sampled every 60 s: (total, errors)
samples = [(10000, 12), (10600, 13), (11250, 15), (11800, 61), (12400, 119), (13010, 177)]

def rate(values, window):
    first, last = values[-window - 1], values[-1]
    return (last - first) / (window * 60)

totals = [s[0] for s in samples]
errors = [s[1] for s in samples]
req_rate = rate(totals, 3)
err_rate = rate(errors, 3)
ratio = err_rate / req_rate
print(f"request rate (3m): {req_rate:.2f}/s")
print(f"error rate   (3m): {err_rate:.2f}/s")
print(f"error ratio: {ratio:.2%}", "-> ALERT HighErrorRatio (> 5%)" if ratio > 0.05 else "-> ok")

restarts = {"api-7d9f-x2k4p": [0, 0, 0, 0], "worker-5c8d-plq2s": [3, 4, 6, 7]}
for pod, counts in restarts.items():
    increase = counts[-1] - counts[0]
    print(f"{pod}: {increase} restarts in 15m", "-> ALERT CrashLooping" if increase >= 3 else "")
request rate (3m): 9.78/s
error rate   (3m): 0.90/s
error ratio: 9.20% -> ALERT HighErrorRatio (> 5%)
api-7d9f-x2k4p: 0 restarts in 15m
worker-5c8d-plq2s: 4 restarts in 15m -> ALERT CrashLooping

The PromQL behind them looks like this:

text
sum(rate(http_requests_total{code=~"5.."}[3m])) / sum(rate(http_requests_total[3m])) > 0.05
increase(kube_pod_container_status_restarts_total[15m]) >= 3

Events

Kubernetes components record Events for notable things: scheduling decisions, image pulls, probe failures, OOM kills, scaling. They are the fastest way to learn why something happened, but they are kept only about one hour by default.

bash
kubectl get events -n shop --sort-by=.lastTimestamp
kubectl get events -n shop --field-selector type=Warning
kubectl events --for pod/api-7d9f-x2k4p        # newer, friendlier command

Sample output:

text
LAST SEEN   TYPE      REASON             OBJECT                    MESSAGE
2m          Normal    Scheduled          pod/api-7d9f-x2k4p        Successfully assigned shop/api-7d9f-x2k4p to demo-worker
2m          Normal    Pulled             pod/api-7d9f-x2k4p        Container image "ghcr.io/acme/api:2.4.0" already present on machine
90s         Warning   Unhealthy          pod/api-7d9f-x2k4p        Readiness probe failed: HTTP probe failed with statuscode: 503
45s         Warning   BackOff            pod/worker-5c8d-plq2s     Back-off restarting failed container worker

Identical events are deduplicated with a count (x3 over 32s). A model of that aggregation:

python · try it yourself
events = [
    (0, "Warning", "Unhealthy", "pod/api-1", "Readiness probe failed"),
    (10, "Warning", "Unhealthy", "pod/api-1", "Readiness probe failed"),
    (12, "Normal", "Pulled", "pod/web-2", "Image already present"),
    (20, "Warning", "Unhealthy", "pod/api-1", "Readiness probe failed"),
    (31, "Warning", "BackOff", "pod/worker-1", "Back-off restarting failed container"),
    (32, "Warning", "Unhealthy", "pod/api-1", "Readiness probe failed"),
]
grouped = {}
for t, typ, reason, obj, msg in events:
    key = (typ, reason, obj, msg)
    first, _, count = grouped.get(key, (t, t, 0))
    grouped[key] = (first, t, count + 1)

for (typ, reason, obj, msg), (first, last, count) in sorted(grouped.items(), key=lambda kv: kv[1][1]):
    when = f"(x{count} over {last - first}s)" if count > 1 else ""
    print(f"{typ:8} {reason:10} {obj:13} {msg} {when}".rstrip())
Normal   Pulled     pod/web-2     Image already present
Warning  BackOff    pod/worker-1  Back-off restarting failed container
Warning  Unhealthy  pod/api-1     Readiness probe failed (x4 over 32s)

Test yourself

Where should a containerised app write its logs?

  1. To /var/log/app.log inside the container
  2. To stdout and stderr
  3. To etcd
  4. To a ConfigMap

Which component provides the data for kubectl top?

  1. Prometheus
  2. metrics-server
  3. CoreDNS
  4. kube-proxy

Why might kubectl get events show nothing about a problem from yesterday?

  1. Events are only kept for about an hour by default
  2. Events are disabled
  3. Only admins can see events
  4. Events are stored in logs