Tutorial

Observability: Logging, Metrics, and Tracing

Build three-pillar observability with structured logs, Prometheus metrics and alerting, and OpenTelemetry traces that connect user requests across services.

On this page

  1. Introduction
  2. The Three Pillars and What Each Is For
  3. Structured Logging
  4. Metrics with Prometheus
  5. Alerting on Symptoms, Not Causes
  6. Distributed Tracing with OpenTelemetry
  7. The RED and USE Methods, and Request Correlation
  8. Cardinality and the Cost of Labels
  9. Conclusion

Introduction

Monitoring tells you when something is wrong; observability tells you why. The distinction matters in a distributed system, where a slow user request might traverse a load balancer, an API, a cache, a database, and a downstream service, and the “slow” is in one of them but the monitoring dashboard shows only an aggregate. Observability is the ability to ask arbitrary questions of a system in production without shipping new code to answer them, and it rests on three pillars: structured logs, metrics, and distributed traces. This article builds all three with a single instrumentation library — OpenTelemetry — so they share context and a request in motion can be followed from the edge to the database and back.

The Three Pillars and What Each Is For

Logs are discrete, timestamped events: “user 42 logged in,” “request to billing failed with 503.” They are high-cardinality and high-volume, good for investigation (“show me everything about request abc123”) and bad for aggregation. Metrics are numeric measurements aggregated over time: request count, error rate, p99 latency, queue depth. They are low-cardinality and cheap to store, good for dashboards and alerting (“is the error rate above 1%?”) and bad for understanding a single request. Traces are the causal chain of a single request across services: the span where the API called the cache, the span where it called the database, the duration of each. They are the bridge — they connect the metric (“p99 is high”) to the logs (“here is the specific slow request and what it did”). You need all three; any one alone leaves a blind spot.

Structured Logging

A structured log is a JSON object with a timestamp, a level, a message, and a context object, not a free-text string. The structure is what makes logs queryable: you filter by level=error and service=api, you group by endpoint, you correlate by requestId. A free-text log is searchable only by substring, which works until it does not.

import pino from "pino";
const logger = pino({
  level: process.env.LOG_LEVEL ?? "info",
  redact: ["req.headers.authorization", "req.headers.cookie", "*.password"], // never log secrets
});

// Per-request logger with context that flows through the request.
app.use((req, res, next) => {
  req.id = crypto.randomUUID();
  req.log = logger.child({ requestId: req.id, userId: req.user?.id, endpoint: req.path });
  next();
});

// Usage: the context is attached automatically.
req.log.info({ durationMs: 42, status: 200 }, "request completed");
req.log.error({ err, userId }, "failed to fetch user");

Three practices make logs useful. Attach a request id to every log line so a request’s logs are a single query. Use a child logger with the request context so every line carries it without manual repetition. Redact secrets at the logger level so a careless log call does not leak a token into the log store. And log at the right level — error for human-investigable failures, warn for handled anomalies, info for normal operation, debug for development — so the signal stands out in the volume.

Metrics with Prometheus

Prometheus is a pull-based metrics system: the application exposes a /metrics endpoint in a text format, and Prometheus scrapes it on an interval. The four metric types cover most needs: a counter for monotonically increasing values (requests total, errors total), a gauge for a current value (queue depth, active connections), a histogram for a distribution (request latency, observed into buckets), and a summary for quantiles on the client side. Use histograms for latency, because quantiles are computed in Prometheus from the buckets and can be aggregated across instances; summaries cannot be aggregated.

import prometheus from "prom-client";

const requestCount = new prometheus.Counter({
  name: "http_requests_total",
  help: "Total HTTP requests",
  labelNames: ["method", "route", "status"],
});
const requestDuration = new prometheus.Histogram({
  name: "http_request_duration_seconds",
  help: "Request duration in seconds",
  labelNames: ["method", "route"],
  buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10], // SLO-aware buckets
});

app.use((req, res, next) => {
  const end = requestDuration.startTimer({ method: req.method, route: req.route?.path ?? "unknown" });
  res.on("finish", () => {
    end();
    requestCount.inc({ method: req.method, route: req.route?.path ?? "unknown", status: String(res.statusCode) });
  });
  next();
});

The cardinality rule is the one most often broken: every unique combination of label values is a separate time series, and a label with unbounded values (the user id, the request path with an id in it) explodes the series count and exhausts Prometheus memory. Label by low-cardinality dimensions (method, route template, status code), never by high-cardinality identifiers. The route should be the template (/users/:id), not the actual path (/users/42).

Alerting on Symptoms, Not Causes

Alert on the user-visible symptoms — the error rate, the p99 latency, the saturation — not on the underlying causes, because the causes change and the symptoms do not. An alert on “database connections exhausted” fires when the database is the problem and is silent when the cache is the problem but the user sees the same slow page. An alert on “p99 latency above 2 seconds for 5 minutes” fires whenever the user is affected, regardless of the cause, and the dashboard tells you the cause. Set the alert threshold at the level where the user is harmed, not where the system is unusual, and give it a sustained window so a single spike does not page you at 3 a.m.

# Alert on the SLO burn rate, not on a raw threshold.
- alert: HighErrorRate
  expr: rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.01
  for: 5m
  labels: { severity: page }
  annotations: { summary: "Error rate above 1% for 5 minutes" }

Distributed Tracing with OpenTelemetry

A trace is a tree of spans, each span a unit of work with a start time, a duration, and attributes. The trace connects the services: the edge span is the user request, its children are the API’s internal operations, their children are the calls to the cache and the database. The trace id propagates through the request headers, so every service that handles a piece of the request adds spans to the same trace, and the result is a single timeline you can read end to end.

import { NodeSDK } from "@opentelemetry/sdk-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";

// Initialize once at startup; auto-instruments HTTP, fetch, and popular libs.
new NodeSDK({
  traceExporter: new OTLPTraceExporter({ url: "http://otel-collector:4318/v1/traces" }),
  serviceName: "api",
}).start();

// Custom span for business logic.
import { trace } from "@opentelemetry/api";
async function chargeCard(userId: string, amount: number) {
  return tracer.startActiveSpan("chargeCard", async (span) => {
    span.setAttribute("userId", userId);
    span.setAttribute("amount", amount);
    try {
      const result = await stripe.charges.create({ amount, currency: "usd", customer: userId });
      span.setAttribute("charge.id", result.id);
      return result;
    } catch (err) {
      span.recordException(err); span.setStatus({ code: 2 }); throw err;
    } finally { span.end(); }
    });
}

The payoff is the slow-request investigation. The metric tells you p99 is high; the trace of a specific slow request shows that the API spent 8ms in its own logic and 1900ms in the database call; the span attributes tell you which query. Without the trace you know it is slow; with the trace you know where and why. Instrument with OpenTelemetry so the traces, metrics, and logs share the same trace id and span context, and a single query in your observability backend pulls all three for the same request.

The RED and USE Methods, and Request Correlation

Structured logs and metrics are the raw material; the methods that interpret them are what make them useful. The RED method (Rate, Errors, Duration) is a framework for the metrics of a request-driven service: measure the rate of requests (requests per second), the error rate (the fraction that fail), and the duration (the latency distribution). These three are the minimum dashboard for any service, because they answer the three questions that matter: is it handling traffic, is it succeeding, and is it fast. A dashboard with RED metrics for each endpoint, each downstream dependency, and the overall service is the dashboard that tells you whether the service is healthy at a glance.

The USE method (Utilization, Saturation, Errors) is the complement for resources: measure the utilization of a resource (the fraction of capacity in use), the saturation (the queue length or contention), and the errors (hardware faults, dropped packets). USE is for the CPU, the disk, the network, the connection pool — the resources the service consumes — while RED is for the service itself. Together they answer “is the service healthy” (RED) and “is it resource-constrained” (USE), and the combination is the complete picture of a service’s operational state.

// RED metrics for an endpoint, recorded on every request.
function recordRED(endpoint: string, status: number, durationMs: number) {
  metrics.increment(`http.requests`, { endpoint });               // Rate
  if (status >= 500) metrics.increment(`http.errors`, { endpoint }); // Errors
  metrics.histogram(`http.duration`, durationMs, { endpoint });     // Duration
}
// USE metrics for the connection pool, recorded periodically.
function recordUSE() {
  metrics.gauge(`pool.utilization`, pool.inUse / pool.size);      // Utilization
  metrics.gauge(`pool.saturation`, pool.waitQueueLength);          // Saturation
  metrics.gauge(`pool.errors`, pool.connectionErrors);             // Errors
}

The saturation metric is the one most often omitted and most often the cause of the incident. A connection pool at 100% utilization is not necessarily a problem — it means every connection is in use, which is efficient — but a growing wait queue (saturation) means requests are waiting for a connection, and that wait is the latency the user feels. A CPU at 90% utilization with a run queue of 2 is fine; a CPU at 90% with a run queue of 20 is saturated and the latency is climbing. Utilization tells you how busy the resource is; saturation tells you whether it is keeping up, and saturation is the leading indicator of the incident that utilization misses.

Request correlation is the thread that ties a log line to the request it came from. Generate a request id at the edge (the load balancer or the API gateway) and propagate it through every service and every log line in the request’s path, so a single request can be traced across the distributed system. The id travels in a header (X-Request-Id), is added to the structured log context in every service, and is carried into downstream calls. With it, a user-reported error and a single log line are enough to find every log line and every span for that request across every service.

// At the edge: generate or accept a request id, attach it to the context.
app.use((req, res, next) => {
  const requestId = req.headers["x-request-id"] ?? crypto.randomUUID();
  req.log = logger.child({ requestId, userId: req.user?.id });
  res.setHeader("x-request-id", requestId);
  next();
});
// In every downstream call: forward the request id.
fetch(url, { headers: { "x-request-id": requestId } });

The request id in the log context means every log line for the request is filterable by a single value, and the same id as a trace correlation means the distributed trace opens at the same point. This is the observability that makes a distributed system debuggable: not a pile of uncorrelated log lines, but a thread that runs through every service the request touched, with the logs, the metrics, and the traces all keyed to the same id. The cost is a header and a log field; the value is the difference between a five-minute investigation and a five-hour one.

Cardinality and the Cost of Labels

The cardinality of a metric label is the number of distinct values it can take, and it is the property that determines whether a metric is cheap or ruinous. A label for endpoint with 50 values is fine; a label for user_id with a million values is a metric explosion — the monitoring system stores a time series per distinct label combination, and a million users times 50 endpoints is 50 million series. High-cardinality labels (user id, request id, email) belong in logs and traces, where each event is stored individually, not in metrics, where each series is stored continuously. The rule is: if the label has more than a few hundred possible values, it is a log attribute, not a metric label. Violating this rule is the most common way to inflate a monitoring bill and degrade the monitoring system’s performance, and it is the mistake that is hardest to undo because the historical data is already stored.

Conclusion

Observability is structured logs for the discrete events, Prometheus metrics for the aggregates and alerting on symptoms, and OpenTelemetry traces for the causal chain across services, all sharing a request context so a single query follows a request from edge to database. Instrument everything with the shared library, keep log and label cardinality bounded, alert on the user-visible symptom with a sustained window, and let the traces connect the metric’s “what” to the log’s “why.” The system you can observe is the system you can operate; the system you cannot is the one you debug by guessing.

Related Examples