Prometheus counter not yielding in custom collector

1.3k Views Asked by At

I am writing this custome collector where I want to add a counter.

#!/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)

But I am getting below error upon yeild

(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))
1

There are 1 best solutions below

1
On

collect returns metric families, not metrics. If you yield each of the results of mymetrics_counter.collect() it'd work.

Also, when you create the Counter its getting registered to the default registry which you don't want in this soft of usage as it'll end up returned twice which is invalid.