Python性能监控项目教程_PrometheusGrafana结合实践

15次阅读

prometheus + grafana 监控 python 应用的核心是定义、暴露和查询指标;常用 prometheus-client 库通过 /metrics http 接口暴露 Counter、Gauge 等指标,Prometheus 抓取后由 Grafana 可视化,支持 rate() 处理重启断点。

Python性能监控项目教程_PrometheusGrafana结合实践

用 Prometheus + Grafana 监控 Python 应用,核心是暴露指标、采集数据、可视化展示。关键不在工具,而在理清指标怎么定义、怎么暴露、怎么查。

Python 服务如何暴露指标

最常用的是 prometheus-client 库,它提供 HTTP 接口(默认 /metrics),返回符合 Prometheus 格式的文本指标。

安装与基础用法:

  • pip install prometheus-client
  • flask/fastapi 中启动一个 MetricsEndpoint 或直接集成 start_http_server(8000)
  • 定义指标类型:Counter(计数)、Gauge(瞬时值)、Histogram(分布)、Summary(分位数)

例如统计请求次数:

立即学习Python免费学习笔记(深入)”;

from prometheus_client import Counter
request_count = Counter('http_requests_total', 'Total HTTP Requests')

# 在请求处理逻辑中调用
request_count.inc()

Prometheus 怎么抓取 Python 指标

修改 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(如 consulkubernetes)动态发现目标
  • 避免将 Python 指标端口直接暴露公网;可通过反向代理或 sidecar 方式接入

Grafana 如何连接和画图

在 Grafana 中添加 Prometheus 数据源(URL 填 http://localhost:9090),然后新建 Dashboard。

写查询语句示例:

  • http_requests_total —— 查看原始计数
  • rate(http_requests_total[5m]) —— 每秒平均请求数
  • python_gc_collection_seconds_sum —— GC 耗时(需启用 Python 的 GC 指标)

推荐组合图表:

  • Requests per second(rate + graph)
  • Response time histogram(用 histogram_quantile 计算 P90/P99)
  • Memory usage(Gauge 类型,如 process_resident_memory_bytes

进阶:自动埋点与错误追踪

手动打点易遗漏。可用以下方式增强:

  • 中间件自动记录 HTTP 请求耗时、状态码(FastAPI/Starlette 自带 BaseHTTPMiddleware
  • prometheus_client.values.MultiProcessValue 支持多进程(如 gunicorn 启动多个 worker)
  • 结合 LoggingCounter,把异常日志转为指标(如 error_count.inc()

不复杂但容易忽略:Python 进程重启后 Counter 会重置,Prometheus 的 rate() 函数能自动处理断点,无需额外干预。

text=ZqhQzanResources