Prometheus + Grafana 是 Python 微服务监控的黄金组合:前者采集存储指标,后者可视化与告警;需理清数据链路——从 Python 应用用 prometheus-client 暴露指标,到 Prometheus 抓取配置,再到 Grafana 建看板与 Alertmanager 设精准报警。
Prometheus + Grafana 是 Python 微服务监控的黄金组合:前者专注高效采集和存储指标,后者负责直观展示与灵活告警。关键不在堆功能,而在理清数据链路——从 Python 应用暴露指标,到 Prometheus 抓取,再到 Grafana 建图与设阈值报警。
Python 微服务需主动暴露指标,最常用的是 prometheus-client 库。它不依赖框架,Flask、FastAPI、甚至纯 HTTP 服务都能快速接入。
pip install prometheus-client
:8001/metrics):from prometheus_client import start_http_server, Counter, Histogram
start_http_server(8001) # 单独端口,不影响主业务
Prometheus 不自动发现服务,需手动配置 scrape_configs。微服务动态部署时,建议结合 Consul 或 Kubernetes Service Discovery,但起步可先写死:
scrape_configs:
- job_name: 'python-api'
static_configs:
- targets: ['192.168.1.10:8001', '192.168.1.11:8001']
/metrics 端点,且返回格式为标准 Prometheus 文本协议honor_labels: true 避免标签冲突;设 scrape_interval: 15s 平衡实时性与开销别一上来就套模板。从三个基础维度入手,每张图解决一个明确问题:
up{job="python-api"}),标红即失联rate(http_requests_total[5m]) 看 QPS,用 histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) 看 P95 延迟rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) 计算错误率所有图表开启 Legend 显示服务名或实例 IP,避免“这根线是谁?”的困惑。
用 Prometheus Alertmanager 管理报警,规则写在 alert.rules 文件里。只设三类真正需要人工介入的规则:
up == 0 for 2m —— 连续 2 分钟不可达才触发histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) > 1.5 and avg_over_time(up[5m]) == 1 —— P95 延迟超 1.5 秒,且服务在线rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.05 for 3m —— 错误率持续 3 分钟超 5%每条报警 rule 必须带 summary 和 description 字段,说明影响范围和初步排查方向(如“检查下游 Redis 连接”),而不是只写“服务慢了”。