
Prometheus 监控 Python 应用终极实战prometheus_client 原生集成与全栈可观测性Python 凭借其生态和开发效率支撑着大量 Web 服务、数据处理和自动化任务。然而内存泄漏、请求延迟抖动、工作进程僵死、异常抛出频率等问题往往在用户投诉后才被察觉。Prometheus 官方为 Python 提供了prometheus_client库能以极低的侵入性将应用内部状态CPU、内存、GC、自定义业务指标暴露为 Prometheus 标准格式。本文将带你从零集成客户端、暴露 /metrics 端点到落地 Grafana 大屏与告警规则让 Python 服务的运行时与业务逻辑全透明。1. 为什么选择 prometheus_client官方库持续维护与 Prometheus 生态无缝对接。极低开销基于内存的注册表采集时仅生成文本不阻塞业务。内置进程 GC 指标无需外部 Exporter 即可获得 Python 进程的 CPU、内存、文件描述符、垃圾回收统计。支持多进程完美适配 Gunicorn、uWSGI 等多 worker 模型通过共享目录实现指标聚合。灵活的自定义Counter、Gauge、Histogram、Summary 四种标准类型标签自定义。2. 快速集成暴露 /metrics 端点2.1 安装pipinstallprometheus-client2.2 最小 Flask 示例fromflaskimportFlaskfromprometheus_clientimportgenerate_latest,CollectorRegistry,multiprocessimportos appFlask(__name__)# 如果是多进程模式需使用多进程收集器见进阶章节# 单进程直接使用默认注册表即可app.route(/metrics)defmetrics():fromprometheus_clientimportREGISTRY,generate_latestreturngenerate_latest(REGISTRY),200,{Content-Type:text/plain; version0.0.4}if__name____main__:app.run(host0.0.0.0,port8080)访问http://localhost:8080/metrics你将看到python_gc_objects_collected_total、process_virtual_memory_bytes等指标。2.3 通用 WSGI 中间件方式对于任何 WSGI 应用如 Django、Pyramid可以使用库自带的make_wsgi_app()fromprometheus_clientimportmake_wsgi_appfromwsgiref.simple_serverimportmake_server# 创建 WSGI 应用挂载到 /metricsmetrics_appmake_wsgi_app()httpdmake_server(,8000,metrics_app)httpd.serve_forever()2.4 Django 集成推荐 django-prometheuspipinstalldjango-prometheus在settings.py中添加INSTALLED_APPS[...django_prometheus,]MIDDLEWARE[django_prometheus.middleware.PrometheusBeforeMiddleware,...django_prometheus.middleware.PrometheusAfterMiddleware,]在urls.py中urlpatterns[...path(metrics,include(django_prometheus.urls)),]即可自动暴露数据库、缓存、请求等指标。3. 内置指标解读prometheus_client自动收集三类指标类别指标前缀说明进程信息process_CPU 时间、虚拟/常驻内存、打开文件描述符、最大文件描述符、进程启动时间等Python GCpython_gc_各代 GC 收集次数、收集对象数、不可达对象数Python 平台python_infoPython 版本、编译器等信息关键 PromQL进程 CPU 使用率rate(process_cpu_seconds_total[5m]) * 100内存使用 (RSS)process_resident_memory_bytes文件描述符使用率process_open_fds / process_max_fds * 100GC 频率第 0 代rate(python_gc_collections_total{generation0}[5m])4. 自定义业务指标4.1 Counter只增不减fromprometheus_clientimportCounter REQUEST_COUNTCounter(http_requests_total,Total HTTP requests,[method,endpoint,status])# 使用REQUEST_COUNT.labels(methodGET,endpoint/api,status200).inc()4.2 Gauge可增可减fromprometheus_clientimportGauge IN_PROGRESSGauge(requests_in_progress,Requests currently processing)# 进入请求IN_PROGRESS.inc()# 完成请求IN_PROGRESS.dec()# 也可以设置固定值TEMPERATUREGauge(room_temperature_celsius,Current temperature)TEMPERATURE.set(23.5)4.3 Histogram延迟分布fromprometheus_clientimportHistogram REQUEST_DURATIONHistogram(http_request_duration_seconds,HTTP request latency,[method,endpoint],buckets(0.01,0.05,0.1,0.5,1,2,5))# 记录观察值REQUEST_DURATION.labels(methodGET,endpoint/api).time()defhandle_request():pass# 业务逻辑PromQL 计算 P95histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))4.4 Summary客户端计算分位数fromprometheus_clientimportSummary REQ_TIMESummary(request_processing_seconds,Time spent processing request)# 直接在服务端计算分位数不建议高基数最佳实践优先使用 Histogram因为 Summary 的分位数无法跨实例聚合。4.5 装饰器自动监控请求fromprometheus_clientimportCounter,Histogramimporttime,functoolsdeftrack_request(func):functools.wraps(func)defwrapper(*args,**kwargs):starttime.time()status200try:returnfunc(*args,**kwargs)exceptException:status500raisefinally:REQUEST_COUNT.labels(func.__name__,status).inc()REQUEST_DURATION.labels(func.__name__).observe(time.time()-start)returnwrapper5. 配置 Prometheus 抓取scrape_configs:-job_name:python-appscrape_interval:15sstatic_configs:-targets:[app-host:8080]labels:app:order-serviceenv:production若使用 Django django-prometheus路径可能是/metrics若单独暴露按实际端口路径配置。6. Grafana 仪表盘推荐Python Metrics DashboardID10467覆盖进程内存、CPU、GC、文件描述符等专为 prometheus_client 设计Gunicorn DashboardID3111若使用 Gunicorn含 worker 状态Django DashboardID11166若使用 django-prometheus自定义面板可使用 Stat Panel 展示在线人数Graph 展示 QPS、错误率、延迟分位数。导入后选择数据源使用app变量过滤服务。7. 告警规则实战groups:-name:python_app_alertsrules:-alert:PythonAppDownexpr:up{jobpython-app} 0for:1mlabels:severity:criticalannotations:summary:Python 应用 {{ $labels.instance }} 不可达-alert:PythonHighMemoryexpr:process_resident_memory_bytes / 1024 / 1024500# 500MBfor:10mlabels:severity:warningannotations:summary:Python 进程内存超过 500MB (当前 {{ $value }} MB)-alert:PythonHighCPUexpr:rate(process_cpu_seconds_total[5m]) * 10080for:10mlabels:severity:warningannotations:summary:Python 进程 CPU 使用率超过 80%-alert:PythonHighFileDescriptorsexpr:process_open_fds / process_max_fds0.8for:5mlabels:severity:warningannotations:summary:文件描述符使用率超过 80%-alert:PythonHigh5xxRateexpr:rate(http_requests_total{status~5..}[5m]) / rate(http_requests_total[5m])0.01for:5mlabels:severity:criticalannotations:summary:HTTP 5xx 错误率超过 1%-alert:PythonHighLatencyexpr:histogram_quantile(0.99,rate(http_request_duration_seconds_bucket[5m]))2for:5mlabels:severity:warningannotations:summary:HTTP 请求 P99 延迟超过 2 秒8. 进阶多进程模式与 Gunicorn 集成Python 应用常通过 Gunicorn 或 uWSGI 以多 worker 运行。默认的 Registry 是进程内存储多 worker 会各自独立计数。prometheus_client提供了多进程模式来解决这个问题。8.1 设置环境变量与目录exportPROMETHEUS_MULTIPROC_DIR/tmp/prometheus_metricsmkdir-p$PROMETHEUS_MULTIPROC_DIR8.2 Gunicorn 配置在 Gunicorn 配置文件中gunicorn.conf.pyimportos bind0.0.0.0:8000workers4preload_appTruedefchild_exit(server,worker):# 清理当前 worker 的指标文件fromprometheus_clientimportmultiprocess multiprocess.mark_process_dead(worker.pid)并且确保在应用启动时例如 Flask 的before_first_request或 Django 的wsgi.py中配置注册表fromprometheus_clientimportCollectorRegistry,multiprocess,generate_latestfromflaskimportFlask,Response appFlask(__name__)defmetrics():registryCollectorRegistry()multiprocess.MultiProcessCollector(registry)# 聚合所有 worker 指标datagenerate_latest(registry)returnResponse(data,mimetypetext/plain)app.add_url_rule(/metrics,metrics,metrics)之后 Prometheus 抓取/metrics时会汇总所有 worker 的指标包括每个 worker 的 GC、内存等。注意多进程模式下Histogram/Summary 分位数的聚合会产生一定误差因为分桶在各个进程中独立累加最终由 Prometheus 的histogram_quantile近似计算。8.3 uWSGI 类似配置uWSGI 需启用lazy-apps true并同样使用PROMETHEUS_MULTIPROC_DIR。9. 性能与安全建议避免高基数标签勿将用户 ID、URL 查询参数等作为标签使用日志上下文替代。控制 Histogram 桶数量桶太多会增加时间序列数量一般 10~15 个桶即可。指标暴露端口保护/metrics端口应仅内网可达或使用反向代理添加 Basic Auth。使用独立的 Registry如果在同一进程内运行多个应用模块各自创建独立的 Registry 以避免指标冲突。Python 3.8 的 GC 指标默认已收集无需额外配置。10. 总结通过prometheus_client任何 Python 应用——无论是轻量级 Flask API、全栈 Django 站点还是异步数据处理脚本——都能以几乎零成本的改动将进程健康、GC 行为、请求延迟和自定义业务指标暴露给 Prometheus。结合 Grafana 仪表盘和 Alertmanager 告警Python 应用的性能瓶颈、内存泄漏、错误突增等问题将在几分钟内被发现和响应。将 Python 服务纳入 Prometheus 可观测体系是构建端到端透明化、可靠性不可或缺的一环。