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

  CREATED BY JENKINSBOT

问题描述

我们需要为自己的应用编写 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