client_python icon indicating copy to clipboard operation
client_python copied to clipboard

Metrics without labels missing breaks some codepath

Open romuald opened this issue 1 year ago • 2 comments

When initialized without labels, it seems that the resulting metrics objects will lack some instance variables.

Minimal example:

from prometheus_client import Gauge, generate_latest

cc = Gauge("dummy_count", "POC")

if __name__ == '__main__':
    cc.set(42)
    print(generate_latest().decode())  # OK

    cc.clear()    # raises

"""
Traceback (most recent call last):
  File "prom_example.py", line 10, in <module>
    cc.clear()    # raises
    ^^^^^^^^^^
  File …/site-packages/prometheus_client/metrics.py", line 213, in clear
    with self._lock:
         ^^^^^^^^^^
AttributeError: 'Gauge' object has no attribute '_lock'
"""

The same code with declared labels will properly clear the metrics data

I came up upon this when adding a new metric and forgetting to add the labels.

(I'm using .clear() to reset the metrics during tests)

romuald avatar Aug 02 '23 08:08 romuald

I've tried to add a _lock: contextlib.contextmanager = contextlib.nullcontext() in MetricWrapperBase

This fixes the problem, but the .clear() does not do anything anyway (it simply creates a _metrics = {} on the object, the values are kept)

Not sure how to properly fix this, or if this is even desirable

romuald avatar Aug 02 '23 09:08 romuald

clear() is indeed not intended for metrics without labels.

You could use e.g. .set(-1) if your tests

roidelapluie avatar Aug 08 '23 09:08 roidelapluie