指标与 Prometheus · 第 12 / 14 章
12实操:从零搭一套 Prometheus + 埋点 + 告警
这一章是把前面 11 章拼成一个能跑的系统。目标不是「跑起来 Prometheus」——
那只需要一条 docker run;目标是一个能被故障注入验证过的告警闭环:
人为制造故障 → 指标变化 → 告警从 Pending 变 Firing → 收到通知的人知道先做什么。
12.1 目标与验收标准
你要交付的东西:一个只做一件事的应用(创建订单),它暴露五组指标; 一个 Prometheus 抓它;一套规则产生 5 条告警;一次注入的故障能把这 5 条中的某一条打到 Firing。
| 要埋的指标 | 类型 | 对应告警 | 告警回答的第一个问题 |
|---|---|---|---|
QPS:http_requests_total | counter | OrdersApiNoTraffic | 是入口挂了还是真的没业务了? |
错误率:http_requests_total{status=~"5.."} 比值 | counter 比值 | OrdersApiErrorBudgetFastBurn | 是不是刚发布了? |
P95/P99:http_request_duration_seconds | histogram | OrdersApiLatencyP99High | 慢在自己还是慢在依赖? |
队列深度:worker_queue_depth | gauge | OrdersApiQueueDepthHigh | 消费停了还是流量涨了? |
依赖耗时:dependency_request_duration_seconds | histogram | OrdersApiDependencySlow | 是哪个依赖变慢了? |
每条告警都必须能回答三个问题:影响谁、先看哪个看板、第一步做什么。
落实方式是把它变成告警规则里的三个注解字段:
impact(影响谁)、dashboard_url(先看哪个看板)、
first_action(第一步做什么)。
三者缺一的规则在 CI 里直接判失败——这样「写得清楚」就成了可以自动检查的约束,
而不是靠自觉。
环境要求:Docker + Docker Compose,4 GB 以上空闲内存。 预计耗时 60–90 分钟,其中大部分时间会花在「告警为什么没触发」上——那正是本章要教的东西。
12.2 环境与目录:五个文件
prom-lab/
├── docker-compose.yml
├── Dockerfile
├── app.py # 被观测的应用
├── prometheus.yml # 采集配置
├── alertmanager.yml # 告警路由
└── rules/
└── orders.yml # 5 条告警规则
services:
prometheus:
image: prom/prometheus:v2.53.0
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=15d
- --web.enable-lifecycle
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./rules:/etc/prometheus/rules:ro
- prom-data:/prometheus
ports: ['9090:9090']
healthcheck:
test: ['CMD', 'wget', '--spider', '-q', 'http://localhost:9090/-/ready']
interval: 10s
alertmanager:
image: prom/alertmanager:v0.27.0
volumes:
- ./alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
ports: ['9093:9093']
app:
build: .
environment:
- FAULT=none
ports: ['8080:8080', '9464:9464']
node-exporter:
image: prom/node-exporter:v1.8.1
ports: ['9100:9100']
volumes:
prom-data:
FROM python:3.12-slim
WORKDIR /app
RUN pip install --no-cache-dir flask prometheus-client
COPY app.py .
EXPOSE 8080 9464
CMD ["python", "app.py"]
12.3 应用埋点:五组指标 + 故障注入开关
应用用 Python + Flask,业务端口 8080,指标端口 9464(分开的端口, 这是第 8 章强调过的实践)。内置一个流量发生器,所以不需要额外的压测工具。
import os, random, threading, time
from flask import Flask, jsonify
from prometheus_client import (Counter, Gauge, Histogram, start_http_server)
# none | errors | slow | dep-slow | queue-full | down
FAULT = os.environ.get("FAULT", "none")
BASE_ERR = 0.005 # 正常水位 0.5% 错误,低于 1.44% 的燃烧率告警阈值
REQ = Counter("http_requests_total", "HTTP 请求总数", ["route", "method", "status"])
LAT = Histogram(
"http_request_duration_seconds", "HTTP 请求耗时", ["route"],
buckets=[0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 10],
)
DEP = Histogram(
"dependency_request_duration_seconds", "依赖调用耗时", ["dep", "result"],
buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 3],
)
QUEUE = Gauge("worker_queue_depth", "等待中的任务数", ["queue"])
OLDEST = Gauge("worker_queue_oldest_seconds", "最老任务的等待时长", ["queue"])
ORDER = Counter("order_created_total", "成功创建的订单数", ["channel"])
app = Flask(__name__)
queue_depth = 0
lock = threading.Lock()
def call_dependency(dep):
"""模拟一次下游调用。返回 True 表示成功。"""
t0 = time.time()
slow_p = 0.6 if (FAULT == "dep-slow" and dep == "payment") else 0.0005
if random.random() < slow_p:
time.sleep(random.uniform(1.0, 2.0))
DEP.labels(dep, "timeout").observe(time.time() - t0)
return False
# 正常情况 5-30ms
time.sleep(random.uniform(0.005, 0.03))
DEP.labels(dep, "ok").observe(time.time() - t0)
return True
def handle(route):
"""一次完整的业务处理;HTTP 路由与内置流量发生器共用同一段代码。"""
global queue_depth
start = time.time()
ok = True
for dep in ("mysql", "redis", "payment"):
ok = call_dependency(dep) and ok
err_p = 0.30 if FAULT == "errors" else BASE_ERR
status = 500 if (random.random() < err_p or not ok) else 200
if FAULT == "slow":
time.sleep(random.uniform(0.6, 1.2))
else:
time.sleep(random.uniform(0.005, 0.02))
if FAULT == "queue-full":
with lock:
queue_depth = min(5000, queue_depth + 2)
if status == 200:
ORDER.labels("app").inc()
REQ.labels(route, "GET", str(status)).inc()
LAT.labels(route).observe(time.time() - start)
return status
@app.route("/api/v1/orders", methods=["GET", "POST"])
def create_order():
status = handle("/api/v1/orders")
return jsonify(ok=status < 400), status
@app.route("/healthz")
def healthz():
return "ok", 200
def consumer():
"""后台消费者:正常每秒处理 20 个任务;FAULT=queue-full 时降到 1 个。"""
global queue_depth
rate = 1 if FAULT == "queue-full" else 20
while True:
with lock:
queue_depth = max(0, queue_depth - rate)
QUEUE.labels("order-worker").set(queue_depth)
OLDEST.labels("order-worker").set(round(queue_depth / 20.0, 3))
time.sleep(1)
def generator():
"""内置流量发生器:约 40 QPS。FAULT=down 时停止,用于演练「无流量」告警。"""
while True:
if FAULT != "down":
for _ in range(random.randint(1, 3)):
handle("/api/v1/orders")
time.sleep(0.05)
if __name__ == "__main__":
start_http_server(9464) # 指标端口,独立于业务端口
threading.Thread(target=consumer, daemon=True).start()
threading.Thread(target=generator, daemon=True).start()
app.run(host="0.0.0.0", port=8080, threaded=True)
三个设计点值得注意:handle() 里的埋点位置保证了「HTTP 请求」和「内置流量」
走的是同一条埋点路径,指标语义唯一;
oldest_seconds 用 depth / 20 近似,
真实系统里应该记录任务入队时间戳;start_http_server(9464) 让指标端点
不经过 Flask 的路由、中间件与访问日志。
12.4 采集与告警规则
global:
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s
external_labels:
cluster: prom-lab
rule_files:
- /etc/prometheus/rules/*.yml
alerting:
alertmanagers:
- static_configs:
- targets: ['alertmanager:9093']
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
- job_name: orders
static_configs:
- targets: ['app:9464']
labels:
env: lab
team: order
# 演示 relabel:把 instance 归一化成不带端口的机器标识,并给环境打上统一标签
relabel_configs:
- source_labels: [__address__]
regex: ([^:]+):\d+
replacement: $1
target_label: node
- target_label: env
replacement: lab
# 抓回来之后丢掉对业务无用的指标,控制基数
metric_relabel_configs:
- source_labels: [__name__]
regex: python_gc_.*|python_info|process_virtual_memory_bytes
action: drop
sample_limit: 20000
- job_name: node
static_configs:
- targets: ['node-exporter:9100']
route:
receiver: default
group_by: [alertname, cluster, team]
group_wait: 10s
group_interval: 1m
repeat_interval: 30m
routes:
- matchers: [severity="critical"]
receiver: oncall
repeat_interval: 10m
- matchers: [severity="warning"]
receiver: tickets
repeat_interval: 4h
receivers:
- name: default
webhook_configs:
- url: http://localhost:5001/hook # 本地演练,换成真实值班通道
- name: oncall
webhook_configs:
- url: http://localhost:5001/hook
- name: tickets
webhook_configs:
- url: http://localhost:5001/hook
inhibit_rules:
# 「无流量」是根因级信号;它存在时不再重复通知下游的延迟/错误告警
- source_matchers: [alertname="OrdersApiNoTraffic"]
target_matchers: [alertname=~"OrdersApi.*"]
equal: [cluster]
注意 relabel_configs 里那条 node 标签:
它把 __address__(app:9464)里的端口去掉后写成
node="app"。这样在跨环境聚合时,instance 仍然保留端口
(排查时有用),而 node 可以用于更粗粒度的分组。
12.5 五条告警规则:每一条都回答三个问题
groups:
- name: orders-api
interval: 15s
rules:
# ① 错误率:用 1h/5m 双窗口燃烧率,而不是固定 1% 阈值
- alert: OrdersApiErrorBudgetFastBurn
expr: |
(sum(rate(http_requests_total{job="orders",status=~"5.."}[1h]))
/ sum(rate(http_requests_total{job="orders"}[1h]))) > 14.4 * 0.001
and
(sum(rate(http_requests_total{job="orders",status=~"5.."}[5m]))
/ sum(rate(http_requests_total{job="orders"}[5m]))) > 14.4 * 0.001
for: 2m
labels:
severity: critical
team: order
dashboard: orders-api-red
annotations:
summary: "订单服务错误预算快速燃烧:5xx 占比 {{ $value | humanizePercentage }}"
impact: "全部下单用户受影响,按当前速度 1 小时烧掉 30 天预算的 2%"
dashboard_url: "http://localhost:9090/graph?g0.expr=rate(http_requests_total%7Bstatus%3D~%225..%22%7D%5B5m%5D)&g0.tab=0"
first_action: "确认 30 分钟内是否有发布;有则立即回滚,无则查 mysql / redis 依赖面板"
runbook_url: "http://localhost:9090/alerts"
# ② 延迟:P99 持续超阈值(注意必须 sum by (le))
- alert: OrdersApiLatencyP99High
expr: |
histogram_quantile(0.99,
sum by (route, le) (rate(http_request_duration_seconds_bucket{job="orders"}[5m]))
) > 0.8
for: 10m
labels:
severity: warning
team: order
dashboard: orders-api-latency
annotations:
summary: "路由 {{ $labels.route }} P99 = {{ $value | humanizeDuration }}(阈值 800ms)"
impact: "用户在等待,尚未大量失败;若不处理会在 10-30 分钟内转化为超时与 5xx"
dashboard_url: "http://localhost:9090/graph?g0.expr=histogram_quantile(0.99%2C%20sum%20by%20(route%2C%20le)%20(rate(http_request_duration_seconds_bucket%5B5m%5D)))&g0.tab=0"
first_action: "比对 dependency_request_duration_seconds 的 P99:依赖慢就去依赖面板,自己慢就看实例资源"
runbook_url: "http://localhost:9090/alerts"
# ③ 队列深度:真正的饱和度信号
- alert: OrdersApiQueueDepthHigh
expr: |
worker_queue_depth{job="orders", queue="order-worker"} > 150
for: 5m
labels:
severity: warning
team: order
dashboard: orders-saturation
annotations:
summary: "订单消费队列深度 {{ $value }}(阈值 150)"
impact: "订单处理开始积压,用户会看到「下单成功但迟迟不确认」"
dashboard_url: "http://localhost:9090/graph?g0.expr=worker_queue_depth&g0.tab=0"
first_action: "先看 worker_queue_oldest_seconds:它也在涨就是消费者卡住,不变则是流量突增,考虑扩副本或限流"
runbook_url: "http://localhost:9090/alerts"
# ④ 依赖耗时:把慢的依赖具体指出来
- alert: OrdersApiDependencySlow
expr: |
histogram_quantile(0.99,
sum by (dep, le) (rate(dependency_request_duration_seconds_bucket{job="orders"}[5m]))
) > 1
for: 10m
labels:
severity: warning
team: order
dashboard: orders-deps
annotations:
summary: "依赖 {{ $labels.dep }} 的 P99 = {{ $value | humanizeDuration }}(阈值 1s)"
impact: "依赖变慢会直接抬高本服务的 P99,最终表现为超时与 5xx"
dashboard_url: "http://localhost:9090/graph?g0.expr=histogram_quantile(0.99%2C%20sum%20by%20(dep%2C%20le)%20(rate(dependency_request_duration_seconds_bucket%5B5m%5D)))&g0.tab=0"
first_action: "打开 {{ $labels.dep }} 自身的看板;若是第三方,先确认是否有公告或限流"
runbook_url: "http://localhost:9090/alerts"
# ⑤ 无流量:QPS 掉到 0(含指标整体消失)
- alert: OrdersApiNoTraffic
expr: |
(sum(rate(http_requests_total{job="orders"}[5m]))
or absent(http_requests_total{job="orders"}) * 0) < 1
for: 5m
labels:
severity: critical
team: order
dashboard: orders-api-red
annotations:
summary: "订单服务 5 分钟内请求速率低于 1/s,当前 {{ $value }}"
impact: "入口无流量:可能是全部实例被摘除、DNS/网关配置错误,或业务真的停了"
dashboard_url: "http://localhost:9090/graph?g0.expr=sum(rate(http_requests_total%5B5m%5D))&g0.tab=0"
first_action: "去 Targets 页面看 up 是否为 1;若 up=0 查应用进程与端口,若 up=1 查入口网关与 DNS"
runbook_url: "http://localhost:9090/alerts"
第 ⑤ 条里的 or absent(...) * 0 值得解释:如果应用整体挂掉、
指标序列在 5 分钟 staleness 之后全部消失,sum(rate(...)) 会返回空而不是 0,
< 1 就变成空值,告警不触发——恰好漏掉了最该告警的场景。
or 的作用是「左边为空时用右边的值补充」,
absent(...) * 0 在序列消失时求值为 0,于是表达式变成 0 < 1,告警正常触发。
# hour() 无参数返回当前小时;标量之间比较必须带 bool 修饰符,结果 0 或 1
(sum(rate(http_requests_total{job="orders"}[5m]))
or absent(http_requests_total{job="orders"}) * 0)
* (hour() >= bool 8)
* (hour() < bool 22)
< 1
12.6 故障注入与端到端验证
先把系统跑起来,确认基线是健康的:
cd prom-lab
docker compose up -d --build
sleep 30
# 1. 应用指标出来了没有(应该能看到 http_requests_total 与桶)
curl -s localhost:9464/metrics | grep -c '^http_requests_total'
curl -s localhost:9464/metrics | grep '^worker_queue_depth'
# 2. Prometheus 抓到了没有
curl -s 'localhost:9090/api/v1/targets?state=active' \
| jq -r '.data.activeTargets[] | "\(.labels.job)\t\(.health)\t\(.lastError)"'
# 3. 基线指标:QPS 约 40,错误率约 0.5%,P99 低于 100ms,队列深度接近 0
curl -s localhost:9090/api/v1/query --data-urlencode 'query=sum(rate(http_requests_total{job="orders"}[5m]))' | jq -r '.data.result[0].value[1]'
curl -s localhost:9090/api/v1/query --data-urlencode 'query=histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{job="orders"}[5m])))' | jq -r '.data.result[0].value[1]'
# 4. 当前告警状态(应该是空的)
curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | "\(.labels.alertname)\t\(.state)"'
然后逐个注入故障,每次只注入一个,观察对应的那条告警:
| 注入方式 | 预期指标变化 | 预期告警 | 从注入到 Firing |
|---|---|---|---|
FAULT=errors docker compose up -d app | 5xx 占比 → 30%,燃烧率 300 | OrdersApiErrorBudgetFastBurn | 约 2–3 分钟 |
FAULT=slow | P99 → 1.2s,P50 约 0.9s | OrdersApiLatencyP99High | 约 10–11 分钟 |
FAULT=dep-slow | dep="payment" 的 P99 → 2s | OrdersApiDependencySlow + LatencyP99High | 约 10–11 分钟 |
FAULT=queue-full | 队列深度 → 数百并持续上涨 | OrdersApiQueueDepthHigh | 约 5–6 分钟 |
FAULT=down | QPS → 0 | OrdersApiNoTraffic | 约 10 分钟(含 staleness) |
# 注入错误故障
FAULT=errors docker compose up -d app
# 每 30 秒看一次状态,会依次看到 inactive → pending → firing
watch -n 30 "curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | \"\(.labels.alertname)\t\(.state)\t\(.activeAt)\""'
# 确认 Alertmanager 也收到了
curl -s localhost:9093/api/v2/alerts | jq -r '.[] | "\(.labels.alertname)\t\(.labels.severity)\t\(.status.state)"'
# 确认通知里的三个问题字段都在(这是本章的验收核心)
curl -s localhost:9093/api/v2/alerts \
| jq -r '.[] | select(.labels.alertname=="OrdersApiErrorBudgetFastBurn") | .annotations | {impact, dashboard_url, first_action}'
# 恢复
docker compose up -d app
预期结果:注入 2–3 分钟后,
curl localhost:9090/api/v1/alerts 里出现
OrdersApiErrorBudgetFastBurn pending,再过约 2 分钟变成 firing;
alertmanager 的 API 里能查到同一条告警并带 severity="critical";
最后一条命令输出的 JSON 里 impact、dashboard_url、first_action
三个字段都有值——这就是「收到就知道该做什么」的可验证定义。
如果告警一直停在 pending 不动,按这个顺序排查:
- 表达式是否为真:把
expr原样粘进 Prometheus 的 Graph 页面, 看它是否返回了非空结果。< 1、and两侧标签是否一致, 是这一类问题的两大来源。 - 表达式是否间歇性为空:如果 Graph 上时有时无,
for的计时器会反复归零,永远进不了 firing。看activeAt是否在不断变化。 - 规则有没有被加载:访问
http://localhost:9090/rules, 确认orders-api这个 group 存在、状态不是err。 配置错误会显示在页面顶部的红色横幅里。 - Alertmanager 是否可达:Prometheus 的
/api/v1/alertmanagers应该返回activeAlertmanagers有一条。如果是空数组,说明alerting段的地址写错了。
某订单系统的队列深度告警写成 worker_queue_depth > 150 for: 5m,
但阈值定得太高:真实积压时深度只在 80–120 之间徘徊,而消费者变慢的表现是
最老任务等待时长从 2 秒涨到 900 秒。
- 09:20 一条毒消息导致消费者线程卡死,深度稳定在 110(因为上游也慢下来了,入队速率同时下降)。
- 深度告警全天未触发。用户投诉从 14:30 开始出现,但都被归因为「用户网络问题」。
- 17:40 有人打开队列面板,看到
worker_queue_oldest_seconds= 29,800 秒 (8.3 小时前的任务还没被处理),才发现消费者从早上就死了。
修复动作是把告警改成建在 worker_queue_oldest_seconds > 60 上:
深度是相对指标,会随入队速率一起变化;等待时长是绝对指标,
只要消费者停了它就单调上涨,无法被掩盖。
这就是「饱和度应该看排队时间而不是队列长度」在告警规则上的具体体现。
每次改规则之后手动注入故障太慢。把第 10 章的
promtool test rules 加进来,用合成序列覆盖「应该告警」与「不应该告警」两种场景,
放进 CI 的每一次提交里:
promtool check rules rules/orders.yml
promtool test rules rules/orders_test.yml
# 校验每条告警都带齐了三问字段
yq '.groups[].rules[] | select(.alert) | {
alert,
has_impact: (.annotations.impact != null),
has_dashboard: (.annotations.dashboard_url != null),
has_first_action: (.annotations.first_action != null)}' rules/orders.yml
最后那条 yq 的输出里任何一个字段是 false,
都应该让 CI 失败。把「写清楚」变成机器检查,是这套体系能长期维持的唯一办法。