如何启用 `gunicorn.instrument.prometheus` 并自定义一个业务指标 `http_request_duration_seconds`?
解读
面试官问的不是“会不会装 Prometheus”,而是考察三件事:
- 你是否知道 Gunicorn 自带的 prometheus 插件 藏在
gunicorn.instrument.prometheus; - 你是否能把插件 真正挂载到 master 进程(国内很多候选人只写配置却不验证端口是否监听);
- 你是否能在 业务代码侧 用官方推荐的
prometheus_client写自定义 Histogram,并保证多进程模型下数据 不漂移、可聚合。
这道题在一线互联网公司(字节、阿里、拼多多)的 P6/P7 面试里出现频率极高,答不好会直接被判定为“只会调参,不会观测”。
知识点
- prometheus 插件加载顺序:必须在
config.py里用preload_app = False或True都允许,但post_fork钩子之前就要import gunicorn.instrument.prometheus。 - 多进程数据一致性:
prometheus_client默认使用CollectorRegistry,多 worker 下必须用multiprocess.Mode(env.pid)方案,否则指标漂移。 - 指标类型选择:请求耗时必须用 Histogram(不是 Summary),因为 Histogram 可以在 Prometheus 端聚合 quantile。
- 国内镜像源:
pip install prometheus-client -i https://pypi.tuna.tsinghua.edu.cn/simple,防止现场安装超时。 - 端口冲突:默认监听
localhost:9200,在阿里云/腾讯云 VPC 里需要把statsd_host或prometheus_addr改成0.0.0.0:9200并开放安全组。
答案
步骤一:启用官方插件
在 gunicorn_conf.py 顶部显式导入插件,让 master 进程启动内置 HTTP 接口:
# gunicorn_conf.py
bind = "0.0.0.0:8000"
workers = 4
worker_class = "sync"
# 关键:导入即生效
import gunicorn.instrument.prometheus
# 默认监听 9200,如需改端口
prometheus_addr = "0.0.0.0:9200"
步骤二:业务侧自定义指标
新建 metrics.py,使用 prometheus_client 的 Histogram 并采用多进程模式:
# metrics.py
import os
from prometheus_client import Histogram, CollectorRegistry, multiprocess
# 必须放在全局,防止重复注册
registry = CollectorRegistry()
if 'PROMETHEUS_MULTIPROC_DIR' in os.environ:
multiprocess.MultiProcessCollector(registry)
http_request_duration_seconds = Histogram(
'http_request_duration_seconds',
'HTTP 请求耗时(业务自定义)',
['method', 'endpoint', 'status'],
buckets=(0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0),
registry=registry
)
步骤三:在 Flask/Django 中埋点
以 Flask 为例,用 after_request 钩子注入耗时:
# app.py
import time
from flask import Flask, request
from metrics import http_request_duration_seconds
app = Flask(__name__)
@app.before_request
def before():
request.start = time.time()
@app.after_request
def after(response):
cost = time.time() - request.start
http_request_duration_seconds.labels(
method=request.method,
endpoint=request.endpoint or 'unknown',
status=response.status_code
).observe(cost)
return response
步骤四:启动命令
确保环境变量指向同一临时目录,否则聚合失败:
export PROMETHEUS_MULTIPROC_DIR=/tmp/gunicorn_prometheus
mkdir -p $PROMETHEUS_MULTIPROC_DIR
gunicorn -c gunicorn_conf.py app:app
步骤五:验证
curl http://localhost:9200/metrics 应能看到:
# HELP http_request_duration_seconds HTTP 请求耗时(业务自定义)
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{method="GET",endpoint="index",status="200",le="0.1"} 42.0
...
出现以上输出即表示 插件 + 自定义指标 全部生效。
拓展思考
- worker 重启后数据漂移:
PROMETHEUS_MULTIPROC_DIR下的*.db文件会随 worker 生命周期增长,国内大厂普遍用 cron+find 定时清理 1 天前文件,或写 sidecar 容器在 Pod 销毁前打包上传 OSS。 - 与 Django 中间件结合:可以写
PrometheusAfterMiddleware,把request.start_time挂在threading.local(),防止 gevent 协程切换时取值错位。 - 高基数问题:
endpoint标签如果带用户 ID 会导致时间线爆炸,面试时可主动提出“用 路由模板 代替实际路径”,如/user/<uid>/order。 - K8s 场景:使用
PodMonitor或ServiceMonitor时,要把 9200 端口命名为metrics,并加prometheus.io/scrape: "true"注解,否则阿里云 Prometheus 服务发现会漏抓。 - 与 Grafana 大盘对接:国内主流模板 ID 为 6676(官方 Gunicorn 大盘),但缺少自定义 Histogram,需自行添加
histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[2m])) by (le))面板,面试时说出这句 PromQL 能直接加分。