Python脚本指标监控Prometheus如何集成

wen 实用脚本 2

Python脚本指标监控:Prometheus集成全流程实战指南

📌 目录导读

  1. 为什么选择Prometheus监控Python脚本?
  2. 核心组件:Python客户端的安装与配置
  3. 指标暴露:从零编写自定义Metrics
  4. 实战案例:监控一个Web爬虫脚本
  5. Prometheus服务端配置与数据抓取
  6. 可视化与告警:Grafana+Alertmanager联动
  7. 常见问题与问答(FAQ)

Python脚本指标监控Prometheus如何集成

为什么选择Prometheus监控Python脚本?

在微服务与分布式系统普及的今天,Python脚本往往承担着数据处理、定时任务、爬虫、机器学习模型推理等关键职责,这些脚本一旦出现性能瓶颈或异常退出,可能直接影响业务,Prometheus凭借其拉取式(Pull)采集模型多维度数据模型内置时间序列数据库,成为监控Python脚本的首选方案。

与传统的日志监控相比,Prometheus集成可实现:

  • 实时指标暴露:无需轮询文件,脚本通过HTTP端点直接暴露运行状态。
  • 灵活告警规则:基于指标值自动触发通知(如CPU超限、任务失败次数)。
  • 历史趋势分析:留存数月的性能数据,便于容量规划与根因定位。

核心组件:Python客户端的安装与配置

Prometheus官方提供Python客户端库prometheus-client,支持四大核心指标类型:Counter、Gauge、Histogram、Summary。

1 安装命令

pip install prometheus-client

2 指标类型速查表

指标类型 适用场景 示例
Counter 累计计数(只增不减) 请求总数、错误总数
Gauge 可增可减的瞬时值 内存使用率、队列长度
Histogram 分布统计(如延迟分位数) API响应时间分布
Summary 滑动窗口内的分位数 可自定义百分位点

3 快速启动:暴露指标端点

from prometheus_client import start_http_server, Counter
import random, time
# 定义一个Counter指标
request_counter = Counter('myapp_requests_total', 'Total requests', ['endpoint'])
# 启动HTTP服务,默认端口8000
start_http_server(8000)
while True:
    request_counter.labels(endpoint='/home').inc()
    time.sleep(random.uniform(0.5, 1.5))

访问http://localhost:8000/metrics即可看到Prometheus格式的指标数据。


指标暴露:从零编写自定义Metrics

1 多指标组合监控

假设我们监控一个数据清洗脚本,需要跟踪:

  • running_status:脚本是否正在运行(Gauge,1=运行,0=停止)
  • records_processed:已处理记录数(Counter)
  • process_duration_seconds:单次处理耗时(Histogram)
from prometheus_client import Gauge, Counter, Histogram, start_http_server
status_gauge = Gauge('data_cleaner_status', '1=running, 0=stopped')
processed_counter = Counter('data_cleaner_records_total', 'Total records processed')
duration_histogram = Histogram('data_cleaner_duration_seconds', 'Processing duration',
                               buckets=(0.1, 0.5, 1.0, 2.0, 5.0, float('inf')))

2 动态标签(Label)的妙用

通过标签区分不同任务类型或数据源:

error_counter = Counter('data_cleaner_errors_total', 'Error count', ['error_type'])
# 记录不同错误类型
error_counter.labels(error_type='timeout').inc()
error_counter.labels(error_type='invalid_data').inc(2)

实战案例:监控一个Web爬虫脚本

1 脚本完整代码

import requests
from prometheus_client import start_http_server, Counter, Gauge, Histogram
# 初始化指标
pages_scraped = Counter('crawler_pages_total', 'Successfully scraped pages')
scrape_duration = Histogram('crawler_scrape_seconds', 'Time to scrape a page')
error_count = Counter('crawler_errors_total', 'Total scrape errors')
queue_size = Gauge('crawler_queue_size', 'Number of URLs in queue')
def scrape_page(url):
    with scrape_duration.time():  # 自动记录耗时
        try:
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                pages_scraped.inc()
            else:
                error_count.labels(error_type='http_error').inc()
        except Exception as e:
            error_count.labels(error_type='exception').inc()
if __name__ == '__main__':
    start_http_server(9090)
    urls = [...]  # 待爬取URL列表
    for url in urls:
        queue_size.set(len(urls))  # 更新队列大小
        scrape_page(url)
        queue_size.dec(1)  # 处理完成减少队列

2 验证指标输出

启动脚本后访问http://localhost:9090/metrics,应看到类似输出:

# HELP crawler_pages_total Successfully scraped pages  
# TYPE crawler_pages_total counter  
crawler_pages_total 35.0  
# HELP crawler_scrape_seconds Time to scrape a page  
# TYPE crawler_scrape_seconds histogram  
crawler_scrape_seconds_bucket{le="0.1"} 0  
crawler_scrape_seconds_bucket{le="0.5"} 12  
...

Prometheus服务端配置与数据抓取

1 prometheus.yml配置示例

在Prometheus安装目录下的prometheus.yml添加job:

scrape_configs:
  - job_name: 'python_scripts'
    static_configs:
      - targets: 
        - 'localhost:9090'   # 爬虫脚本的/metrics端点
        - 'localhost:8000'   # 其他Python指标端点
    # 每15秒采集一次
    scrape_interval: 15s
    # 添加标签区分不同脚本
    metric_relabel_configs:
      - source_labels: [__address__]
        target_label: instance

2 验证数据采集

启动Prometheus(./prometheus --config.file=prometheus.yml),在UI中查询up{job="python_scripts"},若返回1则采集成功。

专业提示:如果脚本部署在Docker容器中,需要使用容器IP或服务发现配置,推荐使用Consul或Kubernetes进行动态发现。


可视化与告警:Grafana+Alertmanager联动

1 Grafana仪表板配置

  1. 添加Prometheus数据源(URL指向Prometheus服务)。
  2. 创建仪表板,使用PromQL查询:
    • 抓取成功率rate(crawler_pages_total[5m])
    • 错误率rate(crawler_errors_total[5m])
    • P99延迟histogram_quantile(0.99, sum(rate(crawler_scrape_seconds_bucket[5m])) by (le))

2 Alertmanager告警规则

在Prometheus配置中添加rule文件:

groups:
  - name: python_alert
    rules:
      - alert: HighErrorRate
        expr: rate(crawler_errors_total[5m]) > 0.1
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "爬虫错误率超过10% (当前: {{ $value }})"

常见问题与问答(FAQ)

Q1: Python脚本临时运行(如Cron任务)如何监控?

A:使用Pushgateway组件,脚本结束时将指标推送到Pushgateway,Prometheus再从Pushgateway抓取,注意:Pushgateway是累加器,需手动清理过期指标。

Q2: 指标端点暴露后,如何防止未授权访问?

A:在反向代理(Nginx)中设置IP白名单或添加Basic Auth验证,Prometheus本身支持--web.auth.file配置认证。

Q3: Histogram与Summary该如何选择?

A:如果需要在服务端聚合后计算分位数,使用Histogram;如果客户端已预计算分位数(如延迟的滑动窗口估算),用Summary更高效,监控脚本场景推荐Histogram,便于跨实例聚合。

Q4: 监控Python内存泄漏有哪些指标?

A:使用Gauge记录process_virtual_memory_bytesprocess_resident_memory_bytes(来自process_exporter),也可通过psutil库获取更多内存统计。

Q5: 如何监控多进程Python应用(如Gunicorn)?

A:使用prometheus_multiproc_dir环境变量,将子进程指标写入共享目录,由父进程统一暴露,示例如下:

export prometheus_multiproc_dir=/tmp/prometheus
gunicorn --workers=4 myapp:app

延伸思考:当脚本数量超过10个时,建议使用Consul进行服务注册与发现,Prometheus自动抓取新增节点的指标端点,对于高并发脚本(如秒杀系统),可将指标通过UDP协议发送到独立的数据收集服务,避免HTTP端点成为性能瓶颈。

集成后验证步骤

  1. 在Prometheus UI中搜索up == 1确认所有目标在线。
  2. 在Grafana中观察指标曲线是否连续无中断。
  3. 手动模拟异常(如停止脚本),测试告警是否准时触发。

抱歉,评论功能暂时关闭!