0

我正在写这个客户收集器,我想在其中添加一个计数器。

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

from prometheus_client import start_http_server
from prometheus_client.core import CollectorRegistry, Counter

class MyCollector():
    def __init__(self):
        self.mymetrics_counter = Counter('observability_total', 'Status of My Services', ['app', 'test'])
        
    def describe(self):
        print("Started: Metrics Collector!")
        return list()
    
    def collect(self):
        self.mymetrics_counter.labels('observability', 'test').inc()
        yield self.mymetrics_counter

if __name__ == '__main__':
    try:
        myregistry = CollectorRegistry()
        myregistry.register(MyCollector())
        start_http_server(port=9100, registry=myregistry)
        while True:
            time.sleep(10)
    except KeyboardInterrupt:
        print("Ended: Metrics Collector!")
        sys.exit(0)

但是我在 yield 时遇到了错误

(venv) test_collector % python mycollector.py
Started: Metrics Collector!
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/wsgiref/handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "/Users/myid/Documents/myproj/workspace/test_collector/venv/lib/python3.9/site-packages/prometheus_client/exposition.py", line 123, in prometheus_app
    status, header, output = _bake_output(registry, accept_header, params)
  File "/Users/myid/Documents/myproj/workspace/test_collector/venv/lib/python3.9/site-packages/prometheus_client/exposition.py", line 105, in _bake_output
    output = encoder(registry)
  File "/Users/myid/Documents/myproj/workspace/test_collector/venv/lib/python3.9/site-packages/prometheus_client/exposition.py", line 179, in generate_latest
    mname = metric.name
AttributeError: ("'Counter' object has no attribute 'name'", prometheus_client.metrics.Counter(observability))
4

1 回答 1

0

collect返回指标族,而不是指标。如果你产生它的每一个结果,mymetrics_counter.collect()它就会起作用。

此外,当您创建Counter其注册到默认注册表时,您不希望在此使用软件中使用它,因为它最终会返回两次,这是无效的。

于 2021-06-12T09:43:39.370 回答