Skip to content

CounterMetricFamily should support exemplars #1062

Closed
@lod

Description

Exemplars are specified as being for Histogram and Counter types, and supported by this client for Histogram and Counter types.

However for custom collectors HistogramMetricFamily supports exemplars, but CounterMetricFamily does not.

Support should be added to CounterMetricFamily.

This shouldn't be too hard, it was added to the underlying layers for HistogramMetricFamily support.

Activity

lod

lod commented on Oct 11, 2024

@lod
ContributorAuthor

Workaround until the MR is released.

from typing import Optional, Union, Sequence, Timestamp
from prometheus_client.core import CounterMetricFamily, Exemplar, Sample


class MyCounterMetricFamily(CounterMetricFamily):
    """
    Standard class doesn't support exemplars, so we hack it in.

    See https://github.com/prometheus/client_python/issues/1062
    """

    def __init__(
        self,
        name: str,
        documentation: str,
        value: Optional[float] = None,
        labels: Optional[Sequence[str]] = None,
        created: Optional[float] = None,
        unit: str = "",
        exemplar: Optional[Exemplar] = None,
    ):
        # Run normal, but don't pass in value
        CounterMetricFamily.__init__(self, name, documentation, None, labels, created, unit)

        if value is not None:
            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:
        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))
added a commit that references this issue on Oct 14, 2024
37cd873
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Participants

    @lod

    Issue actions

      CounterMetricFamily should support exemplars · Issue #1062 · prometheus/client_python