Skip to content

Commit

Permalink
Add exemplar support to CounterMetricFamily (#1063)
Browse files Browse the repository at this point in the history
Fixes #1062

Signed-off-by: David Tulloh <[email protected]>
  • Loading branch information
lod authored Oct 14, 2024
1 parent d7c9cd8 commit 37cd873
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
6 changes: 4 additions & 2 deletions prometheus_client/metrics_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ def __init__(self,
labels: Optional[Sequence[str]] = None,
created: Optional[float] = None,
unit: str = '',
exemplar: Optional[Exemplar] = None,
):
# Glue code for pre-OpenMetrics metrics.
if name.endswith('_total'):
Expand All @@ -127,13 +128,14 @@ def __init__(self,
labels = []
self._labelnames = tuple(labels)
if value is not None:
self.add_metric([], value, created)
self.add_metric([], value, created, exemplar=exemplar)

def add_metric(self,
labels: Sequence[str],
value: float,
created: Optional[float] = None,
timestamp: Optional[Union[Timestamp, float]] = None,
exemplar: Optional[Exemplar] = None,
) -> None:
"""Add a metric to the metric family.
Expand All @@ -142,7 +144,7 @@ def add_metric(self,
value: The value of the metric
created: Optional unix timestamp the child was created at.
"""
self.samples.append(Sample(self.name + '_total', dict(zip(self._labelnames, labels)), value, timestamp))
self.samples.append(Sample(self.name + '_total', dict(zip(self._labelnames, labels)), value, timestamp, exemplar))
if created is not None:
self.samples.append(Sample(self.name + '_created', dict(zip(self._labelnames, labels)), created, timestamp))

Expand Down
15 changes: 15 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,21 @@ def test_counter_labels(self):
self.custom_collector(cmf)
self.assertEqual(2, self.registry.get_sample_value('c_total', {'a': 'b', 'c_total': 'd'}))

def test_counter_exemplars_oneline(self):
cmf = CounterMetricFamily('c_total', 'help', value=23, exemplar={"bob": "osbourne"})
self.custom_collector(cmf)
sample = [c.samples for c in self.registry.collect()][0][0]
self.assertDictEqual({"bob": "osbourne"}, sample.exemplar)

def test_counter_exemplars_add(self):
cmf = CounterMetricFamily('c_total', 'help')
cmf.add_metric([], 12, exemplar={"bob": "osbourne"}, created=23)
self.custom_collector(cmf)
total_sample, created_sample = [c.samples for c in self.registry.collect()][0]
self.assertEqual("c_created", created_sample.name)
self.assertDictEqual({"bob": "osbourne"}, total_sample.exemplar)
self.assertIsNone(created_sample.exemplar)

def test_gauge(self):
self.custom_collector(GaugeMetricFamily('g', 'help', value=1))
self.assertEqual(1, self.registry.get_sample_value('g', {}))
Expand Down

0 comments on commit 37cd873

Please sign in to comment.