python开发exporter,for循环创建创建Gauge报错

python开发exporter,for循环创建创建Gauge报错


#!/usr/bin/python3
import os
import time
import sys
sys.path.append("/usr/local/lib/python3.6/site-packages/")
from prometheus_client import start_http_server,Gauge

def get_dir_num():
        for it in 1,2,3,4:
                ite = str(it)
                ll = f"ll{ite}"
                print(ll)
                dir_num = Gauge(ll,'Calculate the number of directories',['instance', 'port'])
                dir_num.labels(instance='3333333',port='222').set(it)

if __name__ == "__main__":

        start_http_server(8000)
        while True:
                get_dir_num()
                time.sleep(10)
[root@localhost exporter]# python3 test.sh 
ll1
ll2
ll3
ll4
ll1
Traceback (most recent call last):
  File "test.sh", line 26, in <module>
    get_dir_num()
  File "test.sh", line 17, in get_dir_num
    dir_num = Gauge(ll,'Calculate the number of directories',['instance', 'port'])
  File "/usr/local/lib/python3.6/site-packages/prometheus_client/metrics.py", line 373, in __init__
    _labelvalues=_labelvalues,
  File "/usr/local/lib/python3.6/site-packages/prometheus_client/metrics.py", line 143, in __init__
    registry.register(self)
  File "/usr/local/lib/python3.6/site-packages/prometheus_client/registry.py", line 45, in register
    duplicates))
ValueError: Duplicated timeseries in CollectorRegistry: {'ll1'}

第一次走完for循环是没问题的,第二次走for循环变量带入Gauge模块直接报错。

访问url可以看到第一次for循环的结果

img

Gauge 的监控项,只能初始化一次,不然会报 “ValueError:Duplicated timeseries in CollectorRegistry”

一定要先在 Gauge 中初始化标签(比如,['标签1', '标签2']),才能在 labels 中使用(比如,labels(IP='10.0.0.1', HOSTNAME='foobar'))

把这行移到for循环外
dir_num = Gauge('ll1', 'Calculate the number of directories', ['instance', 'port'])
去掉while True死循环就可以了

img


import sys
# !/usr/bin/python3
import time

sys.path.append("/usr/local/lib/python3.6/site-packages/")
from prometheus_client import start_http_server, Gauge


def get_dir_num():
    # Gauge 用法:Gauge('监控项', '监控项说明', ['标签1', '标签2'])
    # Gauge 的监控项,只能初始化一次,不然会报 “ValueError:Duplicated timeseries in CollectorRegistry”
    # 一定要先在 Gauge 中初始化标签(比如,['标签1', '标签2']),才能在 labels 中使用(比如,labels(IP='10.0.0.1', HOSTNAME='foobar'))
    dir_num = Gauge('ll1', 'Calculate the number of directories', ['instance', 'port'])
    for it in 1, 2, 3, 4:
        ite = str(it)
        ll = f"ll{ite}"
        print(ll)
        dir_num.labels(instance='3333333', port='222').set(it)


if __name__ == "__main__":
    start_http_server(8000)
    get_dir_num()
    time.sleep(10)