如何给废弃指标添加prometheus_metric_deprecated标签并生成告警
解读
在国内生产环境,指标一旦上线就会被大量 Grafana 大盘、HPA、SLO、计费链路长期引用,直接下线会导致“误杀”。因此 Prometheus 官方推荐“先打标、再告警、后下线”的三段式废弃流程。面试时,面试官想确认你是否能把“指标生命周期管理”落地到代码、配置、流程三个层面,并兼顾兼容性与可观测性。
知识点
- 指标废弃生命周期:标记(deprecated)→ 告警(consumption detection)→ 删除(major release)
- 打标方式: a. 应用侧:在 Counter/Guage/Histogram 初始化时追加 prometheus_metric_deprecated="true" 固定标签 b. 服务端重标记:使用 metric_relabel_configs 对历史指标统一注入
- 消费侧识别:Grafana 查询、HPA、SLO、Recording Rule 统一过滤 {prometheus_metric_deprecated!="true"} 或利用 label_replace 提示用户
- 告警规则:基于 increase(prometheus_metric_deprecated) 或 absent 组合,通知仍在使用的团队
- 灰度下线:通过 Prometheus 联邦层或 Remote-Write 过滤,逐步减少样本量,降低存储压力
- 合规审计:在阿里/腾讯/字节等内部平台,需对接工单系统,告警必须带责任人、预计下线日期、业务等级
答案
步骤一:指标打标
方案 A(推荐,可控):应用代码里统一封装 MustNewCounterVec 函数,内部自动追加 prometheus_metric_deprecated="true" 并附带 deprecated_since 时间戳标签,方便后续排序。
方案 B(存量指标,不改代码):在 Prometheus 配置段加入
metric_relabel_configs:
- source_labels: [name]
regex: '^(http_request_duration_seconds|foo_bar_total)$'
target_label: prometheus_metric_deprecated
replacement: 'true' - source_labels: [name]
regex: '^(http_request_duration_seconds|foo_bar_total)$'
target_label: deprecated_since
replacement: '2024-06-01'
步骤二:消费侧过滤
Grafana 模板变量默认增加 Custom 选项:Show deprecated metrics,默认关闭,SQL 语句自动拼接 and prometheus_metric_deprecated!="true"。
HPA、SLO YAML 中同样追加该标签过滤,防止误引用。
步骤三:告警规则
groups:
- name: deprecated_metrics_consumption
interval: 5m
rules:- alert: DeprecatedMetricStillInUse
expr: |
sum by (job, instance, name) (
{prometheus_metric_deprecated="true"}
) > 0
for: 1h
labels:
severity: warning
team: sre
annotations:
summary: "业务 {{ labels.job }} 仍在使用废弃指标 {{ labels.name }}"
description: "该指标计划于 2024-09-01 下线,请尽快迁移。责任人:{{ $labels.owner | default "未填写" }}"
- alert: DeprecatedMetricStillInUse
步骤四:流程闭环
- 发出版本公告,工单系统创建“指标下线”任务,关联上述告警
- 每周 SRE 例会 review 仍触发告警的指标,若连续 4 周无消费,则进入“待下线”队列
- 大版本发布前,通过 Remote-Write 的 write_relabel_configs 丢弃 prometheus_metric_deprecated="true" 的样本,完成下线
拓展思考
- 如何自动化发现“无标记但已无人使用”的僵尸指标?
答:结合 Prometheus 的 /api/v1/label/name/values 与 Grafana 的 /api/search 做全量 diff,再配合 Loki 审计日志,输出“零查询 30 天”的指标列表,供评估是否反向追加废弃标记。 - 如果业务方坚持临时使用,如何提供“租赁”机制?
答:在标记基础上再增加 deprecated_ttl="2024-12-31" 标签,告警规则里增加时间判断,到期自动提升为 critical 并抄送总监,确保有人背锅。 - 在 Kubernetes 多集群联邦场景,如何防止废弃指标被联邦层再次聚合?
答:联邦 Prometheus 的 match[] 参数显式排除 {prometheus_metric_deprecated="true"},同时在 Thanos Receive 或 VictoriaMetrics 的 vminsert 阶段做 relabel 丢弃,避免“垃圾进、垃圾出”。