首页 > 解决方案 > 从文件导入数据并将其导出到 Prometheus

问题描述

我想知道如何从文本文件中导入数据,然后将其导出到 Prometheus。我已经完成了一段代码,但目前我尝试在 Prometheus 中显示值,它只显示一个值,而不是我想要的所有值。接下来,我附上一些关于代码和 Prometheus 做了什么的图片,只是为了向您展示一点。我真的不知道没有得到我想要的东西有什么问题。

import os, time

from prometheus_client import start_http_server
from prometheus_client.core import GaugeMetricFamily, REGISTRY

class getParameters(object): # read some parameters from a given file and store them in a Gauge 
    def __init__(self, param):
        self.param = param

    def _readSheet(self):
        thgpt = GaugeMetricFamily('TFM_throughpt', 'Throughpt Measure', labels=['IP','module'])
        for file in os.listdir("."):
            if os.path.isfile(file) and file.startswith("test_", 0, 5):
                try:
                    with open(file,'r',encoding = 'utf-8') as f:
                        line = f.readline()
                        while line:
                            if line:
                                aux = line.split(" ")
                                if ('Thgptup:' in line):
                                    thgpt.add_metric([self.param, 'Upload'],float(aux[1]))
                                elif ('Thgptdown' in line):
                                    thgpt.add_metric([self.param, 'Download'],float(aux[1]))
                                elif ('Thgpt' in line):
                                    thgpt.add_metric([self.param, 'Overall'],float(aux[1]))
                                line = f.readline()

                        yield thgpt

                except Exception as f:
                    print(f)

    def _getParam(self): #just read the sample which has been stored in the  Gauge above
        for data in self._readSheet():
            yield data

    def collect(self):
        for x in self._getParam():
            yield x

        yield GaugeMetricFamily('my_gauge', 'Help text', value=7)

param = 'localhost'
REGISTRY.register(getParameters(param))
print ('Reading is Done!')
start_http_server(8000)

try:
    wait_time = 20.0
    while True:
        time.sleep(wait_time)
except KeyboardInterrupt:
    pass

1

2

接下来你可以看到我想要获得的东西:

3

标签: python-3.xprometheus

解决方案


推荐阅读