0. 选型一览:3 种姿势怎么选?
| 方案 | 适用场景 | 优点 | 缺点 | | --- | --- | --- | | ① start_http_server 独立端口 | 脚本/快速验证 | 零依赖,1 行代码 | 多进程要手动合流 | | ② WSGI 嵌入(Flask/Django) | Web 服务 | 端口复用,可鉴权 | 需改路由 | | ③ Pushgateway 推送 | 短任务/Cron | 拉模式失效时救场 | 需运维 Pushgateway |
下文给出可运行最小示例,按场景直接抄。
1. 姿势一:独立线程暴露 /metrics(最简)
安装
pip install prometheus-client
代码
from prometheus_client import Counter, Histogram, start_http_server
import time, random
# ① 定义指标
req_count = Counter('http_requests_total','Total HTTP requests',['method'])
req_duration = Histogram('http_request_duration_seconds','HTTP latency')
# ② 模拟业务
def handle():
req_count.labels(method='GET').inc()
with req_duration.time():
# 自动记录耗时
time.sleep(random.uniform(0.01,0.5))
# ③ 启动独立线程,监听 8000
start_http_server(8000)
print('Metrics: http://localhost:8000/metrics')
while True:
handle()
time.sleep(1)
访问 http://localhost:8000/metrics 即可看到 Prometheus 标准格式文本。
适合:脚本、定时任务、本地调试。
2. 姿势二:WSGI 嵌入现有 Web 应用(生产推荐)
无需额外端口,直接复用业务端口,天然享受认证/HTTPS。
Flask 版
from flask import Flask, request
from prometheus_client import Counter, generate_latest, CONTENT_TYPE_LATEST
app = Flask(__name__)
counter = Counter(,,[])
():
counter.labels(endpoint=).inc()
():
generate_latest(), , {: CONTENT_TYPE_LATEST}
__name__ == :
app.run(port=)


