如何为指标添加单位并 Grafana 自动识别?

解读

在国内生产级 FastAPI 项目中,指标(metrics)最终要落到 Prometheus → Grafana 链路。面试官问“如何为指标添加单位并 Grafana 自动识别”,并不是让你手写 Grafana 插件,而是考察三件事:

  1. 指标命名与 HELP/TYPE 注释是否符合 Prometheus 社区规范,这是“单位”能被 Grafana 自动解析的前提;
  2. 在 FastAPI 侧如何低成本地把单位写进指标,而不破坏高性能;
  3. 是否了解 Grafana 的“unit override”机制,能在面板里一键识别 ms、MB、QPS 等常用单位,减少运维撕逼。

答不到这三层,会被认为“只会在本地跑个 /metrics,没上过生产”。

知识点

  1. Prometheus 指标命名三段式:namespace_subsystem_unit,例如 http_request_duration_seconds。
  2. OpenMetrics 规范:HELP 字符串里用 Unit: seconds 写法,Grafana 9+ 会优先解析。
  3. FastAPI 集成 prometheus-client 或 starlette-exporter 时,可在 Histogram/Count/Gauge 初始化时把 unit 写进 documentation 参数。
  4. Grafana 的“Standard Options → Unit”支持自动识别:若指标名以 _seconds、_bytes、_ratio 结尾,面板默认会带单位;若 HELP 里写了 Unit: xxx,则识别优先级更高。
  5. 多语言团队场景下,运维只认 Prometheus 规范,不会改 Grafana JSON,因此“命名+HELP”是唯一能跨团队对齐的契约。

答案

步骤一:按 Prometheus 命名规范起名字

from prometheus_client import Histogram

# 单位直接体现在名字里
http_request_duration = Histogram(
    name='fastapi_http_request_duration_seconds',
    documentation='Unit: seconds  # 接口响应时间,包括网络延迟',
    labelnames=['method', 'endpoint', 'status']
)

步骤二:在 FastAPI 中间件里埋点

@app.middleware('http')
async def add_prometheus_obs(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    cost = time.perf_counter() - start
    http_request_duration.labels(
        method=request.method,
        endpoint=request.url.path,
        status=response.status_code
    ).observe(cost)
    return response

步骤三:暴露 /metrics 端点

from prometheus_client import make_asgi_app
metrics_app = make_asgi_app()
app.mount('/metrics', metrics_app)

步骤四:Grafana 端零配置识别

  1. Prometheus 数据源添加后,指标名自带 _seconds,Grafana 新建面板时“Unit”自动显示为“seconds(s)”;
  2. 若运维想强制锁定单位,可在面板 JSON 的“fieldConfig.defaults.unit”写“s”,但通常不需要;
  3. 如果指标名无法带单位(遗留系统),在 HELP 字符串里写 Unit: milliseconds,Grafana 9.3+ 也能识别,无需人工改面板。

通过以上四步,单位信息从代码侧一次性注入,后续任何团队导入 Grafana 都能“自动识别”,无需二次沟通。

拓展思考

  1. 多单位混用:同一条指标链路上可能出现“秒”和“毫秒”,务必统一为基准单位(Prometheus 推荐秒),否则 Grafana 会错误叠加。
  2. 自定义单位:国内业务常用“万笔/秒”,但 Prometheus 没有 wps 单位,此时应写成 _ratio 或 _total,再在 Grafana 侧用“custom units”写“万笔/s”,并写进团队规范文档。
  3. Histogram buckets 与单位联动:如果单位是 seconds,buckets 必须按 0.005、0.01、0.025… 递增,不能写 5、10、25,否则 Grafana 的 heatmap 会数量级错位。
  4. 高并发场景:prometheus-client 默认使用互斥锁,FastAPI 异步协程下容易瓶颈,可启用 prometheus_client.core.REGISTRY = CollectorRegistry(auto_describe=False) 并配合 multiprocess_mode='gunicorn',否则单位再漂亮,拉取 /metrics 也会超时。
  5. 云原生面试加分:阿里可观测团队已开源 o11y-metrics-validator,CI 阶段扫描 HELP 字符串是否含 Unit,若缺失直接阻断合并,能讲出这个实践,可体现国内大厂级规范落地经验。