0. 选型一览:3 种姿势怎么选?
| 方案 | 适用场景 | 优点 | 缺点 | | --- | --- | --- | | ① start_http_server 独立端口 | 脚本/快速验证 | 零依赖,1 行代码 | 多进程要手动合流 | | ② WSGI 嵌入(Flask/Django) | Web 服务 | 端口复用,可鉴权 | 需改路由 | | ③ Pushgateway 推送 | 短任务/Cron | 拉模式失效时救场 | 需运维 Pushgateway |
在 Python 中使用 Prometheus 暴露业务指标的三种主流方案:独立线程服务、WSGI 嵌入 Web 应用以及 Pushgateway 推送。涵盖 Counter、Gauge、Histogram 等指标类型的使用,多进程模式下的指标合流配置,以及 Prometheus 抓取与 Grafana 面板导入的基本步骤。同时提供了常见问题的排查清单,帮助开发者快速实现监控闭环。

| 方案 | 适用场景 | 优点 | 缺点 | | --- | --- | --- | | ① start_http_server 独立端口 | 脚本/快速验证 | 零依赖,1 行代码 | 多进程要手动合流 | | ② WSGI 嵌入(Flask/Django) | Web 服务 | 端口复用,可鉴权 | 需改路由 | | ③ Pushgateway 推送 | 短任务/Cron | 拉模式失效时救场 | 需运维 Pushgateway |
下文给出可运行最小示例,按场景直接抄。
安装
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 标准格式文本。
适合:脚本、定时任务、本地调试。
无需额外端口,直接复用业务端口,天然享受认证/HTTPS。
from flask import Flask, request
from prometheus_client import Counter, generate_latest, CONTENT_TYPE_LATEST
app = Flask(__name__)
counter = Counter('api_invocations_total','Total API calls',['endpoint'])
@app.route('/')
def index():
counter.labels(endpoint='/').inc()
return 'ok'
@app.route('/metrics')
def metrics():
return generate_latest(), 200, {'Content-Type': CONTENT_TYPE_LATEST}
if __name__ == '__main__':
app.run(port=8080)
路由 urls.py:
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST
from django.http import HttpResponse
def metrics(_):
return HttpResponse(generate_latest(), content_type=CONTENT_TYPE_LATEST)
urlpatterns = [
path('metrics', metrics),
...
]
适合:已有 Web 框架、需要统一端口与权限管控。
Prometheus 拉模式对生命周期 < 30s 的脚本不友好,Pushgateway 救场。
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
import time
registry = CollectorRegistry()
duration = Gauge('backup_duration_seconds','Backup runtime', registry=registry)
start = time.time()
# do backup ...
duration.set(time.time()- start)
push_to_gateway('pushgateway:9091', job='mysql_backup', registry=registry)
Pushgateway 不自动删除,需设置 TTL 或脚本结束手动 delete_from_gateway()。
适合:Cron 备份、CI/CD、批量计算。
| 类型 | 场景 | 方法 |
|---|---|---|
| Counter | 只增不减(请求数、订单数) | inc() |
| Gauge | 可增可减(温度、内存) | set() / inc() / dec() |
| Histogram | 延迟/大小分布 | observe(value) |
| Summary | 类似 Histogram,带滑动窗 | observe(value) |
示例:
from prometheus_client import Counter, Gauge, Histogram
c = Counter('requests_total','Total requests',['method'])
g = Gauge('temperature_celsius','Current temp')
h = Histogram('request_duration_seconds','Latency', buckets=(0.1,0.5,1,5))
c.labels(method='GET').inc()
g.set(23.4)
h.observe(0.267)
单进程指标只统计本 Worker,需合流。
from prometheus_client import multiprocess, CollectorRegistry
import os
# ① 启动前设置环境变量
os.environ['prometheus_multiproc_dir']='/tmp/prometheus'
os.makedirs('/tmp/prometheus', exist_ok=True)
# ② 在 worker 里注册
def child_exit(server, worker):
multiprocess.mark_process_dead(worker.pid)
WSGI 入口:
registry = CollectorRegistry()
multiprocess.MultiProcessCollector(registry)
def metrics(request):
return HttpResponse(generate_latest(registry), content_type=CONTENT_TYPE_LATEST)
官方文档称性能损耗 < 2%,可放心开启。
prometheus.yml:
scrape_configs:
- job_name:'python-app'
static_configs:
- targets:['app:8080']
metrics_path:'/metrics'
scrape_interval: 15s
重启 Prometheus,Status → Targets 看到 UP 即成功。
| 现象 | 原因 | 解决 |
|---|---|---|
| metrics 404 | 路由未注册 | 确认 /metrics 返回 200 |
| 指标值一直 0 | 标签未匹配 | labels(**kwargs) 必须与定义一致 |
| 多进程缺数据 | 未开 MultiProcessCollector | 加环境变量与合流代码 |
| 标签维度爆炸 | 把用户 ID 当标签 | 用 Summary 统计,勿用高基维标签 |
独立端口 8000 ← ① 脚本、调试
Web 嵌入 /metrics ← ② 生产、复用端口
Pushgateway 9091 ← ③ 短任务、Cron
建议下一步:给指标加 SLO 告警(rate(requests_total[5m]) > 1000),让监控真正闭环。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online