用 Prometheus + Grafana 监控 Python 应用的核心是定义、暴露和查询指标;常用 prometheus-client 库通过 /metrics HTTP 接口暴露 Counter、Gauge 等指标,Prometheus 抓取后由 Grafana 可视化,支持 rate() 处理重启断点。
用 Prometheus + Grafana 监控 Python 应用,核心是暴露指标、采集数据、可视化展示。关键不在堆工具,而在理清指标怎么定义、怎么暴露、怎么查。
最常用的是 prometheus-client 库,它提供 HTTP 接口(默认 /metrics),返回符合 Prometheus 格式的文本指标。
安装与基础用法:
pip install prometheus-clientMetricsEndpoint 或直接集成 start_http_server(8000)
例如统计请求次数:
from prometheus_client import Counter
request_count = Counter('http_requests_total', 'Total HTTP Requests')
# 在请求处理逻辑中调用
request_count.inc()
修改 Prometheus 配置文件 prometheus.yml,添加 job:
scrape_configs:
- job_name: 'python-app'
static_configs:
- targets: ['localhost:8000']
确保 Python 进程已运行且端口可访问(如用 curl http://localhost:8000/metrics 能看到指标文本)。Prometheus 默认每 15 秒拉取一次。
注意点:
service discovery(如 Consul、Kubernetes)动态发现目标在 Grafana 中添加 Prometheus
数据源(URL 填 http://localhost:9090),然后新建 Dashboard。
写查询语句示例:
http_requests_total —— 查看原始计数rate(http_requests_total[5m]) —— 每秒平均请求数python_gc_collection_seconds_sum —— GC 耗时(需启用 Python 的 GC 指标)推荐组合图表:
histogram_quantile 计算 P90/P99)process_resident_memory_bytes)手动打点易遗漏。可用以下方式增强:
BaseHTTPMiddleware)prometheus_client.values.MultiProcessValue 支持多进程(如 Gunicorn 启动多个 worker)logging 和 Counter,把异常日志转为指标(如 error_count.inc())不复杂但容易忽略:Python 进程重启后 Counter 会重置,Prometheus 的 rate() 函数能自动处理断点,无需额外干预。