利用Python prometheus_client库进行Prometheus监控测试

山海之间
山海之间
发布时间:2026-10-15| 2人浏览过
原创

本文介绍如何使用Python官方prometheus_client库搭建Prometheus监控测试环境。内容涵盖客户端库的安装、基于Summary指标创建HTTP服务、后台运行客户端,以及在Prometheus配置文件中添加scrape_configs以抓取本地8080端口的指标数据,最终验证监控链路的有效性。

Python Prometheus客户端测试环境搭建

为了更直观地理解Prometheus的工作机制,本文将通过Python编写的客户端库进行相关功能的测试验证。

该Python客户端库的GitHub项目地址为https://github.com/prometheus。

根据官方提示,需使用pip命令安装prometheus_client库。

pip3 install prometheus_client

随后参考文档提供的示例代码并进行适当修改,以运行一个基础的客户端服务。

将示例代码保存为文件prometheus_python_client.py。


from prometheus_client import start_http_server, Summary
import random
import time
import sys

# Create a metric to track time spent and requests made.
REQUEST_TIME = Summary ('request_processing_seconds', 'Time spent processing request')


# Decorate function with metric.
@REQUEST_TIME.time ( )
def process_request(t):
    """A dummy function that takes some time."""
    time.sleep (t)


if __name__ == '__main__':
    try:
        if sys.argv[1].isdigit():
            port = sys.argv[1]
        else:
            port = 8080
    except:
        port = 8080

    # Start up the server to expose the metrics.
    start_http_server (8080)
    # Generate some requests.
    while True:
        process_request (random.random ( ))

在后台启动该客户端程序。

pytho3 prometheus_python_client.py 8080 &

此时访问本机8080端口,即可查看到相应的监控指标数据。

curl 127.0.0.1:8080/metrics

访问结果如图所示。

Prometheus服务端配置与指标验证

为了在Prometheus中监控此8080端口的目标,需要对Prometheus的配置文件prometheus.yml进行相应修改。

在scrape_configs配置块中新增一个作业(job)配置。

scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
    static_configs:
      - targets: ["localhost:9090"]
  - job_name: 'python-client'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:8080']
        labels:
          group: 'python-client-group'

重启Prometheus服务后,访问其Web界面,在Expression输入框中输入Python客户端的指标名称并执行查询。

可以看到查询结果与scrape_configs中配置的指标一致。

至此,关于使用Python测试Prometheus实现的文章介绍完毕,更多相关Python测试Prometheus内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。