Python3对接Prometheus

科长
2023-12-31 / 0 评论 / 41 阅读 / 正在检测是否收录...

向Prometheus推送指标

安装依赖:

pip3 install prometheus_client
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

# 创建一个收集器
registry = CollectorRegistry()

# 创建一个Gauge指标
gauge = Gauge('my_custom_metric', 'This is a custom metric', registry=registry)

# 设置指标的值
gauge.set(42)

# 将指标推送到Prometheus网关
push_to_gateway('http://localhost:9091', job='my_job', registry=registry)

在上面的示例中,我们首先创建了一个收集器(CollectorRegistry),然后创建了一个名为my_custom_metric的Gauge指标,并设置了它的值为42。最后,我们使用push_to_gateway函数将指标推送到Prometheus网关。

从Prometheus读取指标

import requests

# 定义Prometheus查询的URL
url = 'http://localhost:9090/api/v1/query'

# 定义查询语句
query = 'up'

# 发送GET请求来获取指标数据
response = requests.get(url, params={'query': query})

# 检查响应状态码
if response.status_code == 200:
    # 提取响应中的指标数据
    data = response.json()['data']['result']

    # 遍历指标数据并打印值
    for metric in data:
        value = metric['value']
        print(f"Metric: {metric['metric']}, Value: {value}")
else:
    print(f"Failed to fetch metrics. Status code: {response.status_code}")

在上面的示例中,我们首先定义了Prometheus查询的URL,然后指定了要查询的指标,这里是up指标,它表示Prometheus中的目标是否正常运行。然后,我们使用requests库发送一个GET请求,并通过params参数将查询语句传递给Prometheus查询API。

如果响应状态码为200,表示请求成功,我们可以从响应中提取指标数据,并使用for循环遍历每个指标的值,并进行打印。

0

评论 (0)

取消