Skip to content
devops.academy

Module 10: Monitoring, Logging & Observability — The Complete Guide

Goal

Everything you've built so far can fail — and will, at 3 AM. Monitoring is how you find out before your users tweet about it. This module covers SLI/SLO/SLA thinking, Prometheus + Grafana + Alertmanager, Loki log aggregation, OpenTelemetry, and how Nagios/Datadog fit — closing the DevOps loop.


1. Why Monitoring, and the Three Pillars of Observability

Without monitoring, this is your incident process: customer emails "site is down" → panic → SSH roulette across servers → find the full disk two hours later. With monitoring: disk crossed 85% → Slack alert at 2 PM → fixed in 10 minutes → customers never knew.

Monitoring answers "is it broken?"; observability answers "why is it broken?" via three complementary signals:

PillarWhat it isAnswersTool here
Metricsnumbers over time (CPU %, req/s, p99 latency)"what & how much?" — cheap, great for alerting/trendsPrometheus
Logstimestamped event records"what exactly happened?" — rich detailLoki (also ELK)
Tracesone request's journey across services"where in the chain is it slow/failing?"OpenTelemetry + Tempo/Jaeger

Real debugging uses all three in sequence: a metric alert fires (checkout error rate 5%) → traces show the payment-service hop failing → its logs show connection pool exhausted. Metric → trace → log is the modern incident path.

Analogy

Think of a hospital ward. Metrics are the vitals monitor beeping at the bedside — cheap, continuous numbers that reveal something is wrong. Logs are the doctor's notes recording exactly what happened and when, and traces follow one patient's whole journey through admissions, radiology, and surgery to find where the delay occurred.


2. SLI, SLO, SLA — Measuring "Working"

  • SLI (Indicator): a measured signal of user experience. "% of requests answered < 300ms with non-5xx status."
  • SLO (Objective): your internal target. "99.9% over 30 days."
  • SLA (Agreement): the contract with customers, with penalties. Always looser than the SLO (SLA 99.5% behind an SLO of 99.9% = safety margin).

The nines, so you feel them: 99% = ~7.3h down/month · 99.9% = ~43min · 99.99% = ~4.3min. Each nine costs roughly 10× the engineering effort — "how many nines?" is a business decision, not an ego contest.

Error budget — the operational genius of SLOs: 99.9% means you're allowed 43 min/month of failure. Budget healthy → ship fast, take risks. Budget burned → freeze features, fix reliability. It converts the eternal dev-vs-ops fight into arithmetic. Alert on burn rate ("at this failure rate we exhaust the month's budget in 6 hours") rather than every blip.

Analogy

An SLO is the ward's agreed standard of care — say, every patient seen within fifteen minutes, 99.9% of the time. The error budget is the small allowance of misses that standard permits: while the allowance is intact, the ward can trial new procedures and move fast; once it is spent, everything stops except restoring reliable care.

Pick SLIs from the user's chair: availability, latency (p95/p99 — never averages: an average of 120ms can hide 10% of users suffering 2s; percentiles can't), error rate, throughput. The RED method per service: Rate, Errors, Duration. USE for machines: Utilization, Saturation, Errors.


3. Prometheus — The Metrics Engine

The de-facto standard, especially with Kubernetes (both are CNCF projects).

Pull model: your services expose a /metrics HTTP endpoint (plain text); Prometheus scrapes every 15–60s and stores time series. Benefits: target down = scrape fails = you know instantly ("up == 0"); config lives centrally; no agents pushing floods.

Analogy

Prometheus is the ward nurse doing rounds: on a fixed schedule she walks bed to bed and reads each patient's vitals off the chart at the foot of the bed. If a bed does not answer, that silence is itself the finding — she knows immediately, instead of waiting to notice that a patient stopped calling out.

Targets expose /metrics

App /metrics · Node exporter (host) · cAdvisor (containers)

Prometheus

scrapes every target on schedule, stores time series, evaluates alert rules

Alertmanager

firing alerts → routes to Slack / PagerDuty

Grafana (dashboards)

pulls data with PromQL queries

A metric with labels (dimensions — the superpower):

text
http_requests_total{method="POST", path="/api/orders", status="500"}  1027

Metric types: Counter (only goes up: requests, errors — query its rate), Gauge (goes both ways: memory, queue depth), Histogram (latency buckets → percentiles).

Exporters — metrics for things that can't expose their own

  • node_exporter — Linux host metrics (CPU, RAM, disk, network). Runs on every machine — as a DaemonSet in K8s (Module 7 paying off).
  • cAdvisor / kubelet — per-container metrics.
  • postgres_exporter, redis_exporter, blackbox_exporter (probes URLs from outside — your uptime check), nginx exporter… everything has one.
  • Your own app: instrument with a Prometheus client library — one middleware gives you RED metrics per endpoint. This is the single highest-value 30 minutes of instrumentation you'll ever do.

PromQL — queries you'll actually run

rate(http_requests_total[5m])                              # req/s over 5m window

sum(rate(http_requests_total{status=~"5.."}[5m]))          # error RATIO (an SLI!)
  / sum(rate(http_requests_total[5m]))

histogram_quantile(0.99,                                    # p99 latency
  sum(rate(http_request_duration_seconds_bucket[5m])) by (le))

(node_filesystem_avail_bytes / node_filesystem_size_bytes) < 0.15   # disk < 15%

up == 0                                                     # anything unreachable

Setup for practice: docker compose with prometheus + node_exporter + your app, scrape config in prometheus.yml; in Kubernetes, install kube-prometheus-stack by Helm — one command deploys Prometheus, Grafana, Alertmanager, exporters, and ServiceMonitor CRDs (an operator! Module 7 again).


4. Alertmanager — From Metric to Phone Buzz

Prometheus evaluates alert rules; Alertmanager routes, groups, deduplicates, silences.

yaml
# alert rule
groups:
  - name: app
    rules:
      - alert: HighErrorRate
        expr: |
          sum(rate(http_requests_total{status=~"5.."}[5m]))
            / sum(rate(http_requests_total[5m])) > 0.02
        for: 5m                    # must persist 5m — kills flappy alerts
        labels: { severity: page }
        annotations:
          summary: "Error rate {{ $value | humanizePercentage }} on {{ $labels.service }}"
          runbook: "https://wiki/runbooks/high-error-rate"

      - alert: DiskWillFillIn4Hours          # PREDICTIVE — alert before the outage
        expr: predict_linear(node_filesystem_avail_bytes[1h], 4*3600) < 0
        for: 15m
        labels: { severity: warn }
yaml
# alertmanager routing
route:
  receiver: slack-warnings
  group_by: [alertname, service]        # 30 pods failing = ONE notification
  routes:
    - match: { severity: page }
      receiver: pagerduty               # wakes a human
receivers:
  - name: slack-warnings
    slack_configs: [{ channel: "#alerts", api_url: "<webhook>" }]
  - name: pagerduty
    pagerduty_configs: [{ service_key: "<key>" }]

Alerting philosophy (this is culture, not config):

  • Page on symptoms (users see errors/latency), ticket on causes (one replica down while the service is fine).
  • Every page must be actionable and link a runbook.
  • Alert fatigue is the killer: too many noisy alerts → humans ignore them → the real one is missed. Fewer, better alerts. Delete alerts nobody acts on.
  • Severity ladder: page (wake someone) / warn (Slack, business hours) / info (dashboard only).

Analogy

A good pager fires when a patient is in trouble, not when a mattress goes missing. Page on symptoms — the patient cannot breathe — and file a ticket for causes like a broken spare monitor. A ward where the pager shrieks all night trains its staff to ignore it, and that is exactly how the one real emergency gets slept through.


5. Grafana — Seeing It

Grafana connects to data sources (Prometheus, Loki, CloudWatch, Postgres…) and renders dashboards; it's the single pane of glass.

Analogy

Grafana is the big board at the nurses' station showing every bed's vitals side by side. During an emergency the whole team gathers around one board instead of sprinting from room to room, and afterwards the chart printouts tell the story of exactly when things started going wrong.

  • Start by importing community dashboards (grafana.com/dashboards): Node Exporter Full (ID 1860), kubernetes-mixin — don't hand-build what exists.
  • Build one service dashboard per app, top row = the SLIs: request rate, error %, p50/p95/p99, saturation. Below: per-endpoint breakdowns, dependency health.
  • Use template variables ($env, $service) so one dashboard serves all environments.
  • Dashboards are JSON → store in Git / provision via ConfigMaps (IaC applies to observability too).
  • During an incident, the dashboard is your shared situation room; after, it illustrates the postmortem.

6. Logging at Scale — Grafana Loki

The problem: 30 containers across 10 nodes; a pod that crashed no longer has logs (kubectl logs gone if the node died). You need logs shipped to central storage.

Loki = "Prometheus for logs": it indexes only labels (app, namespace, level), not full text — dramatically cheaper than Elasticsearch, and queries feel like PromQL. The classic ELK/EFK stack (Elasticsearch full-text indexing, Kibana UI) remains common at enterprises; Loki is the lightweight modern default. Know both names.

Analogy

Loki files the doctors' notes by ward, patient, and severity rather than indexing every word ever written. Finding something means pulling the right folder first and then skimming its pages — far cheaper than maintaining a full library index of every sentence, and almost always what you actually needed anyway.

Pipeline:

text
containers → promtail/alloy (DaemonSet, tails /var/log/pods, attaches K8s labels)
           → Loki (stores; chunks to S3)
           → Grafana Explore (LogQL queries, same UI as metrics!)

LogQL:

{namespace="production", app="api"} |= "error"                  # grep, centralized
{app="api"} | json | status >= 500 | line_format "{{.msg}}"     # parse structured logs
sum(rate({app="api"} |= "error" [5m]))                          # logs → metric → alertable!

Log ingestion from different sources (the outline's demo): promtail also tails plain files on VMs (/var/log/nginx/*.log), receives syslog, and Docker has a Loki logging driver — one query interface over K8s pods, legacy VMs, and network devices.

Structured logging — the practice that multiplies log value: emit JSON, not prose:

json
{"ts":"2026-07-07T14:03:22Z","level":"error","service":"api","trace_id":"abc123",
 "route":"/api/orders","status":500,"duration_ms":1240,"msg":"db connection timeout"}

Now "p95 duration of /api/orders from logs" is a query, not a regex safari. Include trace_id in every line and Grafana links logs ↔ traces in one click. Also: never log secrets/PII (this is an audit finding), and set retention (30d hot, archive to S3) — logs are a real cloud bill.


7. OpenTelemetry & Distributed Tracing

Microservices problem: checkout is slow. Which of the six services in the chain is guilty? Metrics say "slow", logs are per-service islands. Tracing follows one request end-to-end:

TRACE abc123 — POST /checkout (1.8s total)
frontend120ms
cart-service80ms
payment-service1500ms ← the culprit
stripe API1450ms ← actually the *external* call
email-service45ms

Each hop is a span; context propagates via HTTP headers (traceparent). OpenTelemetry (OTel) is the CNCF-standard, vendor-neutral way to produce all three signals: auto-instrumentation libraries (Python/Java/Node often near-zero code) → OTel Collector (receive, batch, transform) → any backend (Tempo, Jaeger, Datadog, X-Ray). Instrument once, switch vendors freely — the whole industry has converged on this.

Analogy

A trace is one patient's wristband followed through the entire hospital: admitted at 9:00, X-ray at 9:20, then a mysterious ninety-minute wait outside surgery. Each department stamps the wristband on arrival and departure, so afterwards you can point at exactly which handoff swallowed the time.

You don't need deep tracing skills yet; you need: what a trace/span is, why OTel matters, and how trace_id stitches the three pillars together.


8. Nagios & Datadog — The Rest of the Landscape

Nagios — the veteran (1999-lineage) check-based monitor: plugins (check_disk, check_http, thousands more) run on schedule, return OK/WARNING/CRITICAL, state changes notify. Host/service model, strong for classic infrastructure (servers up? disk ok? SSL cert expiring?). You'll meet it (or descendants Icinga/Zabbix/CheckMK) in established enterprises. Contrast to internalize: Nagios asks "is X OK right now?" (states); Prometheus records time series (trends, percentiles, rich math).

Datadog — the leading SaaS observability platform: one agent per host, and metrics + logs + traces + dashboards + alerting + 700 integrations appear in a polished UI with zero infrastructure to run. The trade-offs define the buy-vs-build decision you'll face in real jobs: excellent and fast to adopt, but expensive at scale (per-host + per-GB logs + per-million spans — large bills are famous) and vendor lock-in vs. Prometheus/Grafana/Loki's free-but-you-operate-it. Many companies run both worlds; knowing the open stack deeply makes you effective in either.


9. Connecting Every Module (The Wrap-Up)

Watch one alert traverse your entire curriculum:

  1. Alert: CheckoutHighErrorRate pages you (Prometheus rule → Alertmanager → PagerDuty).
  2. Dashboard (Grafana): errors began 14:02 — exactly when CI deployed api v2.4.0 (Module 6 pipeline annotated the deploy on the graph).
  3. Logs (Loki): {app="api"} |= "error" → relation "order_flags" does not exist — a migration didn't run.
  4. Mitigate: kubectl rollout undo deploy/api (Module 7) or redeploy previous tag via pipeline (Module 6). Error rate falls in 90 seconds; error budget barely dented.
  5. Fix forward: PR adds the migration step to the pipeline; CodeQL/tests pass; Terraform-managed infra untouched (Modules 1, 6, 9).
  6. Postmortem: blameless doc — timeline from dashboards, action items: add a canary stage + a synthetic checkout probe (blackbox_exporter).

Detect → diagnose → mitigate → prevent, in minutes, with receipts. That loop is DevOps; every module you studied is one gear in it.

Analogy

This loop is the ward round after every emergency: the team retraces what the monitors showed, what the notes recorded, and how the patient was stabilized, then updates the procedures so the same crisis cannot happen again. The goal is never to blame the night nurse — it is to make next month's emergency boring.


10. Hands-On Project (Do This)

  1. Compose lab: your Module 5 app + prometheus + node_exporter + grafana + loki + promtail in one docker-compose.yml. Instrument the app with a Prometheus client (request counter + duration histogram) and switch it to JSON logs.
  2. Build the service dashboard: rate, error %, p95/p99 (histogram_quantile), plus host CPU/disk from node_exporter. Import dashboard 1860 too.
  3. Alert rules: error-rate > 2% for 5m, disk predict_linear, and up == 0; route through Alertmanager to a Slack webhook. Kill the app container and time your alert.
  4. Loki: query your JSON logs in Grafana Explore; create one metric from logs and alert on it. Add a second source: promtail tailing an nginx access log file.
  5. Kubernetes edition: on your kind/EKS cluster, helm install kube-prometheus-stack and loki-stack; get pods/nodes dashboards and pod logs in one Grafana. Note how node_exporter and promtail run (DaemonSets!).
  6. Load test with ab (Module 6) and watch p99 and CPU respond live; trip the HPA (Module 7) and see scaling on the dashboard.
  7. Write SLOs for your app (availability + latency), turn them into recording rules, and a burn-rate alert.
  8. Stretch: add OTel auto-instrumentation + Tempo; click from a slow trace to its logs via trace_id.

11. Self-Check Questions

  • Define SLI/SLO/SLA with one example each. What is an error budget for?
  • Why alert on p99 latency rather than average? Symptoms vs causes?
  • Pull vs push scraping — and how does Prometheus detect a dead target?
  • Counter vs gauge vs histogram; write PromQL for error ratio and p95 from memory.
  • What do for: in a rule and group_by in Alertmanager each prevent?
  • How is Loki cheaper than Elasticsearch, and what's the trade-off?
  • Why structured (JSON) logs? What does trace_id in log lines enable?
  • Nagios vs Prometheus in one sentence; the Datadog trade-off in one sentence.

The Core Loop Is Complete — One Module Left

Monitoring closes the operational loop: everything you've built can now be seen — detect → diagnose → mitigate → prevent, with receipts. That's the whole engine of DevOps running.

Two job-ready gaps still separate "knows the toolchain" from "on call for it," and they're the final module: operating a stateful database (backups you've actually restored, replication, connection limits, safe migrations) and GitOps with ArgoCD (the pull-based deployment model that's now the K8s standard). Both build directly on what you just learned — Module 12 even alerts on "the backup didn't run" using this exact stack.

Next → Module 12: Databases & GitOps Essentials