「Prometheus」- 编写 Exporter 服务(Python) @20210403

本文档介绍了如何使用Python创建PrometheusExporter服务,以便Prometheus可以抓取监控指标。首先,通过创建虚拟环境并安装prometheus-client库来准备环境。接着,编写一个示例服务,使用prometheus_client库的Summary装饰器来跟踪请求处理时间和次数。最后,启动HTTP服务器并在浏览器中查看暴露的指标。参考GitHub上的prometheus/client_python库获取更多详情。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

我们需要为自己的应用编写 Prometheus Exporter 服务,以允许 Prometheus 抓取监控指标。

该笔记将记录:使用 Python 语言编写 Prometheus Exporter 服务的方法,以及常见问题处理。

解决方案

第一步、创建虚拟环境

mkvirtualenv prometheus-client
workon prometheus-client
pip install --upgrade pip

pip install prometheus-client

第二步、创建 Exporter 服务

# example.py

from prometheus_client import start_http_server, Summary
import random
import time

# 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__':
    # Start up the server to expose the metrics.
    start_http_server(8000)
    # Generate some requests.
    while True:
        process_request(random.random())

第三步、运行并访问该 Exporter 服务

# python example.py

# curl http://localhost:8000/
...
process_max_fds 1024.0
# HELP request_processing_seconds Time spent processing request
# TYPE request_processing_seconds summary
request_processing_seconds_count 0.0
request_processing_seconds_sum 0.0
# HELP request_processing_seconds_created Time spent processing request
# TYPE request_processing_seconds_created gauge
request_processing_seconds_created 1.6163217497696743e+09

参考文献

GitHub - prometheus/client_python: Prometheus instrumentation library for Python applications

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值