Skip to content

Metrics without labels missing breaks some codepath #949

Open

Description

@romuald

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)

Activity

  1. romuald commented on Aug 2, 2023

    @romuald
    ContributorAuthor

    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

  2. roidelapluie commented on Aug 8, 2023

    @roidelapluie
    Member

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions