Prometheus python导出器用于json值

2024-06-16 09:13:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个获取和格式化json响应的场景,然后我想使用Prometheus python客户端将从response获取的json data转换为与Prometheus相关的度量

以下是我尝试过的:

import time
from prometheus_client.core import GaugeMetricFamily, REGISTRY, CounterMetricFamily
from prometheus_client import start_http_server
import requests
import json

class CustomCollector(object):
    def __init__(self):
        pass

    def collect(self):
        response = requests.get('https://api.test.com/v1/data', auth= 
        ('abc@gg.com', 'xxrty'))
        d1=(response.json())
        for key in d1:
           g = GaugeMetricFamily("devicevalue", 'Help text', labels=['datalnddev'])
           g.add_metric([key['appname'], key['value'])
           yield g

if __name__ == '__main__':
    start_http_server(8003)
    REGISTRY.register(CustomCollector())
    while True:
        time.sleep(1)

但这无助于解决这个问题,我不确定如何在这里进行任何帮助都将是巨大的。 普罗米修斯的预期exporter metrics输出


Tags: keyfromimportclientjsonhttpdataserver
1条回答
网友
1楼 · 发布于 2024-06-16 09:13:35

代码的想法很好,但是有一些小错误。 -在json数据中,有一个元素的键为appnamet(末尾有额外的t)。 -在遍历数据时,您忘记按键“app_metric”获取列表 -您应该将标签值转换为字符串,如下面的示例([str(key['appname'])]

import time
from prometheus_client.core import GaugeMetricFamily, REGISTRY, CounterMetricFamily
from prometheus_client import start_http_server
import requests
import json

class CustomCollector(object):
    def __init__(self):
        pass

    def collect(self):
        # response = requests.get('https://api.test.com/v1/data', auth= ('abc@gg.com', 'xxrty'))
        d1 = {
            "app_metric": [
                {
                "appname": 18,
                "value": "0"
                },
                {
                "appname": 12,
                "value": "0"
                },
                {
                "appname": 123,
                "value": "0"
                },
                {
                "appname": 134,
                "value": "0"
                }
            ]
        }
        list_of_metrics = d1["app_metric"]
        for key in list_of_metrics:
           g = GaugeMetricFamily("devicevalue", 'Help text', labels=['datalnddev'])
           g.add_metric([str(key['appname'])], key['value'])
           yield g

if __name__ == '__main__':
    start_http_server(8003)
    REGISTRY.register(CustomCollector())
    while True:
        time.sleep(1)

通过这个例子,我得到了您想要的结果:

# HELP devicevalue Help text
# TYPE devicevalue gauge
devicevalue{datalnddev="18"} 0.0
# HELP devicevalue Help text
# TYPE devicevalue gauge
devicevalue{datalnddev="12"} 0.0
# HELP devicevalue Help text
# TYPE devicevalue gauge
devicevalue{datalnddev="123"} 0.0
# HELP devicevalue Help text
# TYPE devicevalue gauge
devicevalue{datalnddev="134"} 0.0

相关问题 更多 >