← 中文资源

简体中文版本

可观测性:日志、指标与追踪

用结构化日志、Prometheus 指标与告警、OpenTelemetry 追踪构建三大支柱,把用户请求跨服务串联起来。

阅读英文原文

引言

可观测性不是收集尽可能多的数据,而是能够回答未知问题:为什么这个请求慢、为什么这个用户失败、这次发布改变了什么。日志、指标和追踪各有分工。

三大支柱

日志记录离散事件和上下文,指标提供聚合趋势和告警,追踪还原单个请求的调用路径。三者通过 trace id 和 request id 关联,才能从告警下钻到具体请求。

结构化日志

输出 JSON,包含时间、级别、服务、request id、路由、状态和耗时。字段名稳定,敏感信息在 logger 层脱敏。不要用字符串拼接代替字段。

指标与告警

用计数器、直方图和仪表记录流量、错误、延迟和饱和度。对症状告警(错误率、p95 延迟、队列积压),而不是对每个原因告警。设置多窗口燃尽率,减少噪声和迟报。

追踪与关联

用 OpenTelemetry 自动埋点 HTTP 和数据库调用,传播 W3C traceparent,为关键业务添加 span。采样要保留错误和慢请求。在日志中记录 trace id,在指标中使用 exemplar 关联。

方法

RED(Rate、Errors、Duration)适合请求型服务,USE(Utilization、Saturation、Errors)适合资源。无论哪种方法,都要把用户请求与基础设施指标关联起来。

代码示例

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");
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();
});
# 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" }
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(); }
    });
}
// 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
}
// 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 } });