Skip to content

Allow adding arbitrary labels to metrics when generating output #741

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions prometheus_client/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,18 @@ def collect(self):
for collector in collectors:
yield from collector.collect()

def labelled_registry(self, extra_labels):
"""Returns object that collects metrics with additional labels.

Returns an object which upon collect() will return
samples with additional labels given in the dictionary.

Intended usage is:
generate_latest(REGISTRY.labelled_registry(['a_timeseries']))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example is incorrect as it should be passing a dict of constant labels.


Experimental."""
return LabelledRegistry(extra_labels, self)

def restricted_registry(self, names):
"""Returns object that only collects some metrics.

Expand Down Expand Up @@ -128,6 +140,19 @@ def get_sample_value(self, name, labels=None):
return None


class LabelledRegistry:
"""Metric collector registry that applies extra labels to metrics."""

def __init__(self, extra_labels, registry):
self._extra_labels = extra_labels
self._registry = registry

def collect(self):
for metric in self._registry.collect():
metric.samples = [s._replace(labels={**s.labels, **self._extra_labels}) for s in metric.samples]
yield metric


class RestrictedRegistry:
def __init__(self, names, registry):
self._name_set = set(names)
Expand Down
7 changes: 7 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,13 @@ def test_restricted_registry_does_not_yield_while_locked(self):
for _ in registry.restricted_registry(['target_info', 's_sum']).collect():
self.assertFalse(registry._lock.locked())

def test_labelled_registry(self):
extra_labels = {'label1': 'value1'}
registry = CollectorRegistry(extra_labels)
Counter('c_total', 'help', registry=registry)
metrics = list(registry.labelled_registry(extra_labels).collect())
self.assertEqual(metrics[0].samples[0].labels, extra_labels)


if __name__ == '__main__':
unittest.main()