Skip to content
Draft
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: 21 additions & 4 deletions prometheus_client/openmetrics/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,12 +231,13 @@ def _format_simple_samples_2_0(metric, family_name, escaping):
return ''.join(_format_sample_2_0(family_name, s, escaping) for s in metric.samples)


def _format_sample_2_0(family_name, sample, escaping):
"""Formats a sample as ``name{labels} value [timestamp]``, named after its family as OpenMetrics 2.0 requires."""
def _format_sample_2_0(family_name, sample, escaping, start_timestamp=None, exemplar=''):
line = f'{_format_name_and_labels_2_0(family_name, sample.labels, escaping)} {floatToGoString(sample.value)}'
if sample.timestamp is not None:
line += f' {sample.timestamp}'
return line + '\n'
if start_timestamp is not None:
line += f' st@{start_timestamp}'
return line + exemplar + '\n'


def _format_name_and_labels_2_0(name, labels, escaping):
Expand All @@ -254,7 +255,23 @@ def _format_name_and_labels_2_0(name, labels, escaping):


def _format_counter_2_0(metric, family_name, escaping):
raise NotImplementedError('OpenMetrics 2.0 does not support counter metrics yet')
created_name = metric.name + '_created'
start_timestamps = {
frozenset(sample.labels.items()): sample.value
for sample in metric.samples if sample.name == created_name
}
output = []
for sample in metric.samples:
if sample.name == created_name:
continue
if sample.name != family_name:
raise ValueError(f'Unexpected counter sample name {sample.name!r} in {family_name!r}')
exemplar = ''
if sample.exemplar is not None and sample.exemplar.timestamp is not None:
exemplar = _compose_exemplar_string(metric, sample, sample.exemplar)
start_timestamp = start_timestamps.get(frozenset(sample.labels.items()))
output.append(_format_sample_2_0(family_name, sample, escaping, start_timestamp, exemplar))
return ''.join(output)


def _format_summary_2_0(metric, family_name, escaping):
Expand Down
31 changes: 29 additions & 2 deletions tests/openmetrics/test_exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
CollectorRegistry, Counter, Enum, Gauge, Histogram, Info, Metric, Summary,
)
from prometheus_client.core import (
BucketSpan, Exemplar, GaugeHistogramMetricFamily, GaugeMetricFamily,
HistogramMetricFamily, NativeHistogram, Timestamp, UnknownMetricFamily,
BucketSpan, CounterMetricFamily, Exemplar, GaugeHistogramMetricFamily,
GaugeMetricFamily, HistogramMetricFamily, NativeHistogram, Timestamp,
UnknownMetricFamily,
)
from prometheus_client.openmetrics.exposition import (
_generate_latest_2_0, ALLOWUTF8, DOTS, escape_label_name,
Expand Down Expand Up @@ -541,6 +542,32 @@ def collect(self):

self.registry.register(CustomCollector())

def test_counter_start_timestamps(self) -> None:
c = CounterMetricFamily('requests_total', 'Requests', labels=['method'])
c.add_metric(['GET'], 4, created=1520430000.123)
c.add_metric(['POST'], 2, created=0)
c.add_metric(['PUT'], 1)
self.custom_collector(c)
self.assertEqual(b"""# TYPE requests_total counter
# HELP requests_total Requests
requests_total{method="GET"} 4.0 st@1520430000.123
requests_total{method="POST"} 2.0 st@0
requests_total{method="PUT"} 1.0
# EOF
""", _generate_latest_2_0(self.registry, UNDERSCORES))

def test_counter_exemplars(self) -> None:
c = CounterMetricFamily('requests', 'Requests', labels=['method'])
c.add_metric(['GET'], 4, created=100, timestamp=123, exemplar=Exemplar({'trace_id': 'abc'}, 3, 120))
c.add_metric(['POST'], 2, exemplar=Exemplar({'trace_id': 'xyz'}, 1))
self.custom_collector(c)
self.assertEqual(b"""# TYPE requests_total counter
# HELP requests_total Requests
requests_total{method="GET"} 4.0 123 st@100 # {trace_id="abc"} 3.0 120
requests_total{method="POST"} 2.0
# EOF
""", _generate_latest_2_0(self.registry, UNDERSCORES))

def test_gauge(self) -> None:
g = Gauge('gg', 'A gauge', registry=self.registry)
g.set(17)
Expand Down