Part 6 ยท Chapter 19

Metrics & Logs: Watching Your App's Heartbeat

Prometheus, Grafana, Loki, and the ELK stack โ€” see exactly what's happening inside your production system, before your users tell you something is wrong.

What you'll learn in this chapter

  • The three pillars of observability and why each one matters
  • How Prometheus scrapes metrics and the four metric types: Counter, Gauge, Histogram, Summary
  • How to expose metrics from a Node.js application using prom-client
  • PromQL โ€” Prometheus's query language โ€” for asking real production questions
  • How to set up alerting with Prometheus Alertmanager and route alerts to Slack or PagerDuty
  • Grafana dashboards: turning raw numbers into beautiful, actionable visualizations
  • Structured logging and why console.log strings are not enough in production
  • Grafana Loki for Kubernetes-native log aggregation and the PLG stack
  • The ELK stack (Elasticsearch, Logstash, Kibana) and when to choose it over Loki

The Hospital Monitoring Room Analogy

Imagine a patient in intensive care. Doctors don't wander past and guess whether the patient is doing well. They don't wait for the patient to press a call button saying "something feels off." Instead, there are monitors on the wall showing heart rate, blood pressure, oxygen saturation, respiratory rate, and temperature โ€” all in real time, all on a single screen. The moment any measurement crosses a threshold, an alarm goes off. A nurse sees it and says: "Heart rate has been elevated for 20 minutes. Let's investigate before this becomes a crisis."

Your production application is the patient. Observability tools are the monitoring room. Without them, you're flying blind. You find out about problems when customers email you or when the phone rings at 2 AM. With observability, you find out the moment something starts going wrong โ€” often before any user even notices โ€” because the numbers tell the story.

๐Ÿฅ The Three Pillars of Observability

Modern observability rests on three complementary pillars. Each answers a different question about your running system:

  • Metrics โ€” Numbers over time. CPU is at 72%. Response time is 230ms. Error rate is 0.1%. Memory is 4.2 GB of 8 GB. Metrics are cheap to store, fast to query, and perfect for alerting on thresholds. They tell you that something is wrong.
  • Logs โ€” Text records of events. "User alice@example.com logged in at 14:32:11." "ERROR: Database connection failed after 3 retries." "Payment processed for order #8823." Logs are richer than metrics and tell you what happened.
  • Traces โ€” The path a request takes through multiple services. A user taps "Buy Now" and the request bounces through six microservices before a response arrives. Which service was the bottleneck? Traces answer why something was slow. (We cover traces in depth in the next chapter.)

A mature observability setup uses all three. They complement each other like a medical chart (metrics), a doctor's notes (logs), and an MRI scan (traces).

Prometheus โ€” The Metrics Database

Prometheus is an open-source monitoring system that collects metrics by scraping โ€” it periodically visits your application at a /metrics HTTP endpoint and reads the numbers. Instead of your application pushing data to a central server, Prometheus pulls the data on a schedule. This inversion is intentional: it means Prometheus knows when an application has stopped responding (it simply fails to scrape), and it keeps the application itself simple.

This pull model is like a supervisor who walks around the factory floor every 15 seconds checking every machine, rather than machines constantly sending messages to the supervisor. The supervisor sees a machine that has gone quiet and immediately knows something is wrong.

๐Ÿ“– The Four Prometheus Metric Types
  • Counter โ€” A number that only ever goes up. It resets to zero when the process restarts. Perfect for: total HTTP requests served, total errors encountered, total bytes transferred. You never ask "what is the counter value?" โ€” you ask "how fast is it increasing?" using rate().
  • Gauge โ€” A number that can go up or down. Perfect for: current active connections, current memory usage, current queue depth, current number of running goroutines. A thermometer is a gauge.
  • Histogram โ€” Tracks distributions by putting observations into pre-defined buckets. Perfect for: request duration, response size. You define buckets like "less than 10ms", "less than 100ms", "less than 1 second". Histograms let you calculate percentiles (p95, p99) on the Prometheus server side.
  • Summary โ€” Similar to a histogram but calculates quantiles on the client side before sending to Prometheus. Less flexible than histograms for aggregation across instances but simpler to configure.

What Metrics Look Like at the /metrics Endpoint

Prometheus metrics are exposed as plain text at /metrics. Each metric has a name, a type comment, a help comment, and one or more time-series with optional labels. Labels are the key-value pairs in curly braces โ€” they let you slice the same metric by different dimensions (by HTTP method, by status code, by route, by region).

# HELP http_requests_total The total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="GET",status="200"} 4823
http_requests_total{method="GET",status="404"} 12
http_requests_total{method="POST",status="500"} 3

# HELP node_memory_MemFree_bytes Free memory in bytes
# TYPE node_memory_MemFree_bytes gauge
node_memory_MemFree_bytes 1.2e+09

# HELP http_request_duration_seconds HTTP request duration in seconds
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.01"} 324
http_request_duration_seconds_bucket{le="0.1"} 1204
http_request_duration_seconds_bucket{le="1.0"} 1518
http_request_duration_seconds_bucket{le="+Inf"} 1521
http_request_duration_seconds_sum 87.32
http_request_duration_seconds_count 1521

Exposing Metrics from Node.js with prom-client

The prom-client library makes it easy to add Prometheus metrics to any Node.js application. It also provides collectDefaultMetrics() which automatically exposes 30+ metrics about the Node.js runtime: CPU usage, event loop lag, garbage collection, memory heap, open file descriptors, and more โ€” for free, with one function call.

// metrics.ts โ€” Prometheus metrics setup
import { Registry, Counter, Histogram, collectDefaultMetrics } from 'prom-client';

export const register = new Registry();

// Automatically collect CPU, memory, event loop lag, GC stats, etc.
collectDefaultMetrics({ register });

export const httpRequests = new Counter({
  name: 'http_requests_total',
  help: 'Total number of HTTP requests',
  labelNames: ['method', 'route', 'status'],
  registers: [register],
});

export const requestDuration = new Histogram({
  name: 'http_request_duration_seconds',
  help: 'HTTP request duration in seconds',
  labelNames: ['method', 'route'],
  buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5],
  registers: [register],
});

export const activeConnections = new Gauge({
  name: 'http_active_connections',
  help: 'Number of active HTTP connections',
  registers: [register],
});
// app.ts โ€” wire up metrics middleware
import express from 'express';
import { register, httpRequests, requestDuration, activeConnections } from './metrics';

const app = express();

// Middleware: record every request's duration and status
app.use((req, res, next) => {
  const end = requestDuration.startTimer({
    method: req.method,
    route: req.path,
  });
  activeConnections.inc();

  res.on('finish', () => {
    httpRequests.inc({
      method: req.method,
      route: req.path,
      status: res.statusCode.toString(),
    });
    end();
    activeConnections.dec();
  });
  next();
});

// Prometheus scrapes this endpoint every 15 seconds
app.get('/metrics', async (req, res) => {
  res.set('Content-Type', register.contentType);
  res.end(await register.metrics());
});

app.listen(3000);

Prometheus Configuration โ€” prometheus.yml

Prometheus reads a YAML configuration file that tells it which targets to scrape and how often. Each job_name is a logical grouping of targets. Prometheus ships with dozens of exporters โ€” standalone processes that expose metrics for things that can't export their own: Linux system metrics (node-exporter), PostgreSQL, Redis, MySQL, Nginx, and more.

# prometheus.yml
global:
  scrape_interval: 15s        # How often to scrape each target
  evaluation_interval: 15s    # How often to evaluate alert rules

scrape_configs:
  - job_name: 'my-api'
    static_configs:
      - targets: ['my-api:3000']  # service name in Docker / Kubernetes

  - job_name: 'node-exporter'    # CPU, disk, memory, network of each host
    static_configs:
      - targets: ['node-exporter:9100']

  - job_name: 'postgres'
    static_configs:
      - targets: ['postgres-exporter:9187']

  - job_name: 'redis'
    static_configs:
      - targets: ['redis-exporter:9121']

# Tell Prometheus where to find alerting rules
rule_files:
  - 'alerts/*.yml'

PromQL โ€” Asking Questions About Your Metrics

PromQL (Prometheus Query Language) is how you query your metrics. It looks strange at first, but it has a clear logic: every query starts with a metric name, optionally filtered by labels, and then transformed by functions. The most important function is rate() โ€” it takes a counter (which only goes up) and calculates how fast it's increasing per second.

# Requests per second over the last 1 minute
rate(http_requests_total[1m])

# Error rate: 5xx requests per second over the last 5 minutes
rate(http_requests_total{status=~"5.."}[5m])

# Percentage of requests that are errors (last 5 minutes)
rate(http_requests_total{status=~"5.."}[5m])
  /
rate(http_requests_total[5m]) * 100

# 95th percentile response time over the last hour
histogram_quantile(0.95,
  sum(rate(http_request_duration_seconds_bucket[1h])) by (le)
)

# CPU usage percentage (inverting the "idle" metric)
100 - (avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

# Memory used (total minus free)
node_memory_MemTotal_bytes - node_memory_MemFree_bytes

# Free disk space percentage
(node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100
๐Ÿ’ก The Golden Signals

Google's Site Reliability Engineering book defines the "Four Golden Signals" โ€” four metrics that, if you instrument nothing else, tell you almost everything you need to know about your service's health:

  • Latency โ€” How long does it take to serve a request? Track p50, p95, p99.
  • Traffic โ€” How many requests per second is the service handling?
  • Errors โ€” What percentage of requests are failing?
  • Saturation โ€” How full is the service? CPU at 95%, disk at 90%, connection pool exhausted?

Start with these four. Add more only when these don't answer your questions.

Alerting with Prometheus Alertmanager

Prometheus evaluates alert rules on a schedule. When a rule's condition is true for a defined duration, it fires an alert. Alertmanager then routes that alert to the right place: Slack for low-severity warnings, PagerDuty for critical incidents that wake someone up.

Alert rules live in YAML files. The for field is crucial โ€” it means "only fire if this condition is true for at least this long." Without it, a brief spike would page an engineer unnecessarily.

# alerts/my-app.yml
groups:
  - name: my-app
    rules:
      - alert: HighErrorRate
        expr: rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.05
        for: 2m    # must be true for 2 minutes before firing
        labels:
          severity: critical
        annotations:
          summary: "High error rate detected on {{ $labels.job }}"
          description: "Error rate is {{ $value | humanizePercentage }} (threshold: 5%)"

      - alert: HighMemoryUsage
        expr: (node_memory_MemTotal_bytes - node_memory_MemFree_bytes) / node_memory_MemTotal_bytes > 0.9
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Memory usage above 90% on {{ $labels.instance }}"

      - alert: SlowResponseTime
        expr: histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) > 1.0
        for: 3m
        labels:
          severity: warning
        annotations:
          summary: "p95 response time exceeds 1 second"

      - alert: DiskSpaceLow
        expr: (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100 < 10
        for: 10m
        labels:
          severity: critical
        annotations:
          summary: "Disk space is below 10% on {{ $labels.instance }}"

Grafana โ€” Beautiful Dashboards

Prometheus is the brain; Grafana is the eyes. Grafana connects to Prometheus (and dozens of other data sources) and lets you build rich visual dashboards: time-series graphs, single-stat panels showing current values, heatmaps, tables, and more. It's open source, runs as a web app, and teams share dashboards using JSON files checked into Git.

The best place to start is Grafana's dashboard library at grafana.com/grafana/dashboards. Need a PostgreSQL dashboard? Download ID 9628. Need a Node.js dashboard? Download ID 11159. In five minutes you have professional dashboards without writing a single PromQL query.

๐Ÿ“– Grafana Core Concepts
  • Data Source โ€” a connection to a backend: Prometheus, Loki, CloudWatch, InfluxDB, PostgreSQL, Elasticsearch. One Grafana instance can connect to many data sources simultaneously.
  • Dashboard โ€” a collection of panels arranged on a grid. Saved as JSON, shareable, version-controllable.
  • Panel โ€” a single visualization: a time-series graph, a stat (big number), a gauge, a table, a heatmap, a log viewer.
  • Variables โ€” dropdown selectors at the top of a dashboard that filter all panels. A $service variable lets one dashboard cover all your microservices.
  • Alerts โ€” Grafana can also evaluate alert rules and notify Slack, PagerDuty, email, etc., without needing Alertmanager.

Docker Compose: Full Monitoring Stack

Here's a complete Docker Compose stack to run Prometheus, Grafana, and Node Exporter locally. Bring it up with docker compose up -d and visit Grafana at http://localhost:3001 (login: admin / admin).

# docker-compose.yml โ€” Monitoring Stack
services:
  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - ./alerts:/etc/prometheus/alerts
      - prometheus_data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.retention.time=15d'

  grafana:
    image: grafana/grafana:latest
    ports:
      - "3001:3000"
    environment:
      GF_SECURITY_ADMIN_PASSWORD: admin
      GF_USERS_ALLOW_SIGN_UP: "false"
    volumes:
      - grafana_data:/var/lib/grafana
    depends_on:
      - prometheus

  node-exporter:
    image: prom/node-exporter:latest
    ports:
      - "9100:9100"
    volumes:
      - /proc:/host/proc:ro
      - /sys:/host/sys:ro
      - /:/rootfs:ro
    command:
      - '--path.procfs=/host/proc'
      - '--path.sysfs=/host/sys'
      - '--collector.filesystem.ignored-mount-points=^/(sys|proc|dev|host|etc)($$|/)'

  alertmanager:
    image: prom/alertmanager:latest
    ports:
      - "9093:9093"
    volumes:
      - ./alertmanager.yml:/etc/alertmanager/alertmanager.yml

volumes:
  prometheus_data: {}
  grafana_data: {}

Logs โ€” Your Application's Diary

Logs are the narrative of what happened. When a customer says "my payment failed around 3 PM yesterday," logs are how you find out exactly what happened. But to be useful in production โ€” especially across dozens of containers and microservices โ€” logs need to be structured, not free-form strings.

A structured log is a JSON object. Every important value has a named key. This means log analysis tools can filter by any field instantly, without trying to parse arbitrary text with regular expressions.

Unstructured vs Structured Logging

Bad (unstructured):
console.log("User logged in: alice@example.com at 14:32:11 from 196.1.2.3")

Good (structured JSON):
{ "event": "user.login", "userId": "user_123", "email": "alice@example.com",
  "ipAddress": "196.1.2.3", "duration_ms": 45, "level": "info",
  "timestamp": "2026-05-06T14:32:11.234Z" }

Popular structured logging libraries: Pino (Node.js โ€” extremely fast, JSON by default), Winston (Node.js โ€” flexible, many transports), structlog (Python), Loguru (Python), Zap (Go).

// Using Pino for structured logging in Node.js
import pino from 'pino';

const logger = pino({
  level: process.env.LOG_LEVEL || 'info',
  // In production, output JSON; in development, pretty-print
  transport: process.env.NODE_ENV !== 'production'
    ? { target: 'pino-pretty' }
    : undefined,
});

// Child logger adds context fields to every log line
export function createRequestLogger(requestId: string, userId?: string) {
  return logger.child({ requestId, userId });
}

// Usage in a service
async function processOrder(orderId: string, userId: string) {
  const log = logger.child({ orderId, userId });
  log.info({ event: 'order.processing_started' });

  try {
    const result = await chargePayment(orderId);
    log.info({ event: 'order.payment_success', amount: result.amount });
  } catch (err) {
    log.error({ event: 'order.payment_failed', err }, 'Payment failed');
    throw err;
  }
}

Grafana Loki โ€” Logs for the Kubernetes Generation

Grafana Loki is a log aggregation system inspired by Prometheus. Its core philosophy: index the labels, not the content. Elasticsearch indexes every word in every log line (powerful but expensive). Loki only indexes labels like app="my-api", namespace="production", pod="my-api-7d5f9c-k4j2p". Log content is stored compressed and searched with grep-like scanning. This makes Loki drastically cheaper to run while still being fast for most real-world queries.

๐Ÿ“š The Library Card Catalogue Analogy

Elasticsearch is like a library where every single word in every book has been indexed โ€” finding any phrase is instant but building and maintaining that index is expensive and takes lots of space.

Loki is like a library that only indexes the author, title, genre, and year. Finding books by those fields is fast. Reading the actual content requires walking to the shelf and scanning the pages โ€” but for most questions ("show me all logs from the payment service that mention 'error'") that scanning is plenty fast enough, and the library is far cheaper to build and maintain.

The PLG stack (Prometheus + Loki + Grafana) is the modern Kubernetes-native observability stack. All three tools are from Grafana Labs, they share the same label model, and Grafana provides a unified query interface for both metrics and logs in the same dashboard.

Loki Architecture

PLG Stack Data Flow

Application containers write logs to stdout
↓
Promtail (agent on every Kubernetes node) tails container log files
↓
Loki stores logs, indexed by labels
↓
Grafana queries Loki with LogQL, displays alongside Prometheus metrics

LogQL โ€” Querying Logs

# Get all logs from the my-api app in the last hour
{app="my-api"}

# Filter to only error logs
{app="my-api"} |= "error"

# Parse JSON logs and filter by field values
{app="my-api"} | json | level="error"

# Find slow requests (duration > 1000ms) using JSON parsing
{app="my-api"} | json | duration_ms > 1000

# Count error log lines per minute over last hour
count_over_time({app="my-api"} | json | level="error" [1m])

# Filter by multiple labels (namespace + app)
{namespace="production", app="payment-service"} |= "FAILED"

# Extract a field and filter (regex)
{app="my-api"} | json | event =~ "order\\..*"

The ELK Stack โ€” The Traditional Choice

The ELK stack predates Loki by nearly a decade. It stands for Elasticsearch + Logstash + Kibana. Elasticsearch is a powerful distributed search engine built on Apache Lucene. Logstash collects logs from hundreds of sources (files, syslog, HTTP, Kafka, database CDC streams), transforms them with filter plugins, and ships them to Elasticsearch. Kibana is the visualization and query interface.

In practice, teams often replace Logstash with the much lighter Filebeat or Fluentd (giving you the "EFK" stack), because Logstash is resource-intensive. Since 2021, Amazon has also maintained OpenSearch โ€” a fully open-source fork of Elasticsearch, created when Elastic changed its license.

๐Ÿ“– ELK vs Loki โ€” When to Use Each
  • Choose Loki when: you're already using Prometheus and Grafana, you're running on Kubernetes, you want lower cost and simpler operations, your main use case is debugging and monitoring rather than full-text search.
  • Choose ELK/OpenSearch when: you need full-text search across log content, you have compliance or audit log requirements, you ingest logs from many non-Kubernetes sources, you need sophisticated log parsing pipelines (Logstash filter plugins are extremely powerful).
  • Both work well for most production use cases. The ecosystem matters more than raw feature comparison โ€” pick the one your team already knows, or the one that integrates with your existing stack.
๐ŸŒ Real-World Scale

Prometheus was created at SoundCloud in 2012 and donated to the CNCF in 2016. It is now one of the most widely deployed pieces of infrastructure software in the world โ€” running at Netflix, Uber, DigitalOcean, GitLab, and thousands of other companies. Grafana serves over 10 million active dashboards globally. Elasticsearch powers the search on Wikipedia, GitHub, and Stack Overflow.

Chapter Summary

  • The three pillars of observability are Metrics (numbers over time), Logs (event text records), and Traces (request journeys across services).
  • Prometheus collects metrics by scraping a /metrics endpoint on each service every 15 seconds. It has four metric types: Counter, Gauge, Histogram, and Summary.
  • PromQL lets you query metrics with functions like rate() (for counters) and histogram_quantile() (for percentiles). Start with the four Golden Signals: Latency, Traffic, Errors, Saturation.
  • Alertmanager routes Prometheus alerts to Slack, PagerDuty, or email based on severity. The for field prevents false alarms from transient spikes.
  • Grafana is the visualization layer โ€” it connects to Prometheus (and Loki, and many other sources) and turns raw metrics into dashboards. Use the Grafana dashboard library to get started fast.
  • Structured logging (JSON) is essential in production. Libraries like Pino (Node.js) or structlog (Python) make it easy to log key-value pairs that tools can filter and query.
  • Grafana Loki stores logs indexed by labels (not content), making it far cheaper than Elasticsearch. The PLG stack (Prometheus + Loki + Grafana) is the modern Kubernetes-native observability standard.
  • The ELK stack remains the best choice when you need full-text search, compliance audit logs, or sophisticated log transformation pipelines.