# opentelemetry.sdk.metrics package

## Submodules

- opentelemetry.sdk.metrics.export
  - `AggregationTemporality`
    - `AggregationTemporality.UNSPECIFIED`
    - `AggregationTemporality.DELTA`
    - `AggregationTemporality.CUMULATIVE`
  - `Buckets`
    - `Buckets.offset`
    - `Buckets.bucket_counts`
  - `ConsoleMetricExporter`
    - `ConsoleMetricExporter.export()`
    - `ConsoleMetricExporter.shutdown()`
    - `ConsoleMetricExporter.force_flush()`
  - `InMemoryMetricReader`
    - `InMemoryMetricReader.get_metrics_data()`
    - `InMemoryMetricReader.shutdown()`
  - `MetricExporter`
    - `MetricExporter.export()`
    - `MetricExporter.force_flush()`
    - `MetricExporter.shutdown()`
  - `MetricExportResult`
    - `MetricExportResult.SUCCESS`
    - `MetricExportResult.FAILURE`
  - `MetricReader`
    - `MetricReader._receive_metrics()`
    - `MetricReader.collect()`
    - `MetricReader.force_flush()`
    - `MetricReader.shutdown()`
  - `PeriodicExportingMetricReader`
    - `PeriodicExportingMetricReader.shutdown()`
    - `PeriodicExportingMetricReader.force_flush()`
  - `ExponentialHistogram`
    - `ExponentialHistogram.data_points`
    - `ExponentialHistogram.aggregation_temporality`
    - `ExponentialHistogram.to_json()`
  - `ExponentialHistogramDataPoint`
    - `ExponentialHistogramDataPoint.attributes`
    - `ExponentialHistogramDataPoint.start_time_unix_nano`
    - `ExponentialHistogramDataPoint.time_unix_nano`
    - `ExponentialHistogramDataPoint.count`
    - `ExponentialHistogramDataPoint.sum`
    - `ExponentialHistogramDataPoint.scale`
    - `ExponentialHistogramDataPoint.zero_count`
    - `ExponentialHistogramDataPoint.positive`
    - `ExponentialHistogramDataPoint.negative`
    - `ExponentialHistogramDataPoint.flags`
    - `ExponentialHistogramDataPoint.min`
    - `ExponentialHistogramDataPoint.max`
    - `ExponentialHistogramDataPoint.exemplars`
    - `ExponentialHistogramDataPoint.to_json()`
  - `Gauge`
    - `Gauge.data_points`
    - `Gauge.to_json()`
  - `Histogram`
    - `Histogram.data_points`
    - `Histogram.aggregation_temporality`
    - `Histogram.to_json()`
  - `HistogramDataPoint`
    - `HistogramDataPoint.attributes`
    - `HistogramDataPoint.start_time_unix_nano`
    - `HistogramDataPoint.time_unix_nano`
    - `HistogramDataPoint.count`
    - `HistogramDataPoint.sum`
    - `HistogramDataPoint.bucket_counts`
    - `HistogramDataPoint.explicit_bounds`
    - `HistogramDataPoint.min`
    - `HistogramDataPoint.max`
    - `HistogramDataPoint.exemplars`
    - `HistogramDataPoint.to_json()`
  - `Metric`
    - `Metric.name`
    - `Metric.description`
    - `Metric.unit`
    - `Metric.data`
    - `Metric.to_json()`
  - `MetricsData`
    - `MetricsData.resource_metrics`
    - `MetricsData.to_json()`
  - `NumberDataPoint`
    - `NumberDataPoint.attributes`
    - `NumberDataPoint.start_time_unix_nano`
    - `NumberDataPoint.time_unix_nano`
    - `NumberDataPoint.value`
    - `NumberDataPoint.exemplars`
    - `NumberDataPoint.to_json()`
  - `ResourceMetrics`
    - `ResourceMetrics.resource`
    - `ResourceMetrics.scope_metrics`
    - `ResourceMetrics.schema_url`
    - `ResourceMetrics.to_json()`
  - `ScopeMetrics`
    - `ScopeMetrics.scope`
    - `ScopeMetrics.metrics`
    - `ScopeMetrics.schema_url`
    - `ScopeMetrics.to_json()`
  - `Sum`
    - `Sum.data_points`
    - `Sum.aggregation_temporality`
    - `Sum.is_monotonic`
    - `Sum.to_json()`
- opentelemetry.sdk.metrics.view
  - `Aggregation`
  - `DefaultAggregation`
  - `DropAggregation`
  - `ExplicitBucketHistogramAggregation`
  - `ExponentialBucketHistogramAggregation`
  - `LastValueAggregation`
  - `SumAggregation`
  - `View`

class opentelemetry.sdk.metrics.AlignedHistogramBucketExemplarReservoir(boundaries, **kwargs)

  Bases: `FixedSizeExemplarReservoirABC`

  This Exemplar reservoir takes a configuration parameter that is the configuration of a Histogram. This implementation keeps the last seen measurement that falls within a histogram bucket.

  Reference:

    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#alignedhistogrambucketexemplarreservoir

  offer(value, time_unix_nano, attributes, context)

    Offers a measurement to be sampled.

    Return type:

      `None`

class opentelemetry.sdk.metrics.AlwaysOnExemplarFilter

  Bases: `ExemplarFilter`

  An ExemplarFilter which makes all measurements eligible for being an Exemplar.

  Reference:

    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#alwayson

  should_sample(value, time_unix_nano, attributes, context)

    Returns whether or not a reservoir should attempt to filter a measurement.

    Parameters:

      - value (`int` | `float`) – The value of the measurement

      - timestamp – A timestamp that best represents when the measurement was taken

      - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – The complete set of measurement attributes

      - context (`Context`) – The Context of the measurement

    Return type:

      `bool`

class opentelemetry.sdk.metrics.AlwaysOffExemplarFilter

  Bases: `ExemplarFilter`

  An ExemplarFilter which makes no measurements eligible for being an Exemplar.

  Using this ExemplarFilter is as good as disabling Exemplar feature.

  Reference:

    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#alwaysoff

  should_sample(value, time_unix_nano, attributes, context)

    Returns whether or not a reservoir should attempt to filter a measurement.

    Parameters:

      - value (`int` | `float`) – The value of the measurement

      - timestamp – A timestamp that best represents when the measurement was taken

      - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – The complete set of measurement attributes

      - context (`Context`) – The Context of the measurement

    Return type:

      `bool`

class opentelemetry.sdk.metrics.Exemplar(filtered_attributes, value, time_unix_nano, span_id=None, trace_id=None)

  Bases: `object`

  A representation of an exemplar, which is a sample input measurement.

  Exemplars also hold information about the environment when the measurement was recorded, for example the span and trace ID of the active span when the exemplar was recorded.

  Variables:

    - trace_id – (optional) The trace associated with a recording

    - span_id – (optional) The span associated with a recording

    - time_unix_nano – The time of the observation

    - value – The recorded value

    - filtered_attributes – A set of filtered attributes which provide additional insight into the Context when the observation was made.

  References

  https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md#exemplars https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#exemplar

  filtered_attributes: Mapping[str, str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]] | None
  value: int | float
  time_unix_nano: int
  span_id: int | None = None
  trace_id: int | None = None

class opentelemetry.sdk.metrics.ExemplarFilter

  Bases: `ABC`

  `ExemplarFilter` determines which measurements are eligible for becoming an `Exemplar`.

  Exemplar filters are used to filter measurements before attempting to store them in a reservoir.

  Reference:

    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#exemplarfilter

  abstractmethod should_sample(value, time_unix_nano, attributes, context)

    Returns whether or not a reservoir should attempt to filter a measurement.

    Parameters:

      - value (`int` | `float`) – The value of the measurement

      - timestamp – A timestamp that best represents when the measurement was taken

      - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – The complete set of measurement attributes

      - context (`Context`) – The Context of the measurement

    Return type:

      `bool`

class opentelemetry.sdk.metrics.ExemplarReservoir

  Bases: `ABC`

  ExemplarReservoir provide a method to offer measurements to the reservoir and another to collect accumulated Exemplars.

  Note

  The constructor MUST accept `**kwargs` that may be set from aggregation parameters.

  Reference:

    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#exemplarreservoir

  abstractmethod offer(value, time_unix_nano, attributes, context)

    Offers a measurement to be sampled.

    Parameters:

      - value (`int` | `float`) – Measured value

      - time_unix_nano (`int`) – Measurement instant

      - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – Measurement attributes

      - context (`Context`) – Measurement context

    Return type:

      `None`

  abstractmethod collect(point_attributes)

    Returns accumulated Exemplars and also resets the reservoir for the next sampling period

    Parameters:

      point_attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – The attributes associated with metric point.

    Return type:

      `list`[`Exemplar`]

    Returns:

      a list of `opentelemetry.sdk.metrics._internal.exemplar.exemplar.Exemplar` s. Returned exemplars contain the attributes that were filtered out by the aggregator, but recorded alongside the original measurement.

class opentelemetry.sdk.metrics.Meter(instrumentation_scope, measurement_consumer, *, _meter_config=None)

  Bases: `Meter`

  See `opentelemetry.metrics.Meter`.

  create_counter(name, unit='', description='')

    Creates a `Counter` instrument

    Parameters:

      - name – The name of the instrument to be created

      - unit – The unit for observations this instrument reports. For example, `By` for bytes. UCUM units are recommended.

      - description – A description for this instrument and what it measures.

    Return type:

      `Counter`

  create_up_down_counter(name, unit='', description='')

    Creates an `UpDownCounter` instrument

    Parameters:

      - name – The name of the instrument to be created

      - unit – The unit for observations this instrument reports. For example, `By` for bytes. UCUM units are recommended.

      - description – A description for this instrument and what it measures.

    Return type:

      `UpDownCounter`

  create_observable_counter(name, callbacks=None, unit='', description='')

    Creates an `ObservableCounter` instrument

    An observable counter observes a monotonically increasing count by calling provided callbacks which accept a `CallbackOptions` and return multiple `Observation`.

    For example, an observable counter could be used to report system CPU time periodically. Here is a basic implementation:

        def cpu_time_callback(options: CallbackOptions) -> Iterable[Observation]:
            observations = []
            with open("/proc/stat") as procstat:
                procstat.readline()  # skip the first line
                for line in procstat:
                    if not line.startswith("cpu"): break
                    cpu, *states = line.split()
                    observations.append(Observation(int(states[0]) // 100, {"cpu": cpu, "state": "user"}))
                    observations.append(Observation(int(states[1]) // 100, {"cpu": cpu, "state": "nice"}))
                    observations.append(Observation(int(states[2]) // 100, {"cpu": cpu, "state": "system"}))
                    # ... other states
            return observations

        meter.create_observable_counter(
            "system.cpu.time",
            callbacks=[cpu_time_callback],
            unit="s",
            description="CPU time"
        )

    To reduce memory usage, you can use generator callbacks instead of building the full list:

        def cpu_time_callback(options: CallbackOptions) -> Iterable[Observation]:
            with open("/proc/stat") as procstat:
                procstat.readline()  # skip the first line
                for line in procstat:
                    if not line.startswith("cpu"): break
                    cpu, *states = line.split()
                    yield Observation(int(states[0]) // 100, {"cpu": cpu, "state": "user"})
                    yield Observation(int(states[1]) // 100, {"cpu": cpu, "state": "nice"})
                    # ... other states

    Alternatively, you can pass a sequence of generators directly instead of a sequence of callbacks, which each should return iterables of `Observation`:

        def cpu_time_callback(states_to_include: set[str]) -> Iterable[Iterable[Observation]]:
            # accept options sent in from OpenTelemetry
            options = yield
            while True:
                observations = []
                with open("/proc/stat") as procstat:
                    procstat.readline()  # skip the first line
                    for line in procstat:
                        if not line.startswith("cpu"): break
                        cpu, *states = line.split()
                        if "user" in states_to_include:
                            observations.append(Observation(int(states[0]) // 100, {"cpu": cpu, "state": "user"}))
                        if "nice" in states_to_include:
                            observations.append(Observation(int(states[1]) // 100, {"cpu": cpu, "state": "nice"}))
                        # ... other states
                # yield the observations and receive the options for next iteration
                options = yield observations

        meter.create_observable_counter(
            "system.cpu.time",
            callbacks=[cpu_time_callback({"user", "system"})],
            unit="s",
            description="CPU time"
        )

    The `CallbackOptions` contain a timeout which the callback should respect. For example if the callback does asynchronous work, like making HTTP requests, it should respect the timeout:

        def scrape_http_callback(options: CallbackOptions) -> Iterable[Observation]:
            r = requests.get('http://scrapethis.com', timeout=options.timeout_millis / 10**3)
            for value in r.json():
                yield Observation(value)

    Parameters:

      - name – The name of the instrument to be created

      - callbacks – A sequence of callbacks that return an iterable of `Observation`. Alternatively, can be a sequence of generators that each yields iterables of `Observation`.

      - unit – The unit for observations this instrument reports. For example, `By` for bytes. UCUM units are recommended.

      - description – A description for this instrument and what it measures.

    Return type:

      `ObservableCounter`

  create_histogram(name, unit='', description='', *, explicit_bucket_boundaries_advisory=None)

    Creates a `Histogram` instrument

    Parameters:

      - name (`str`) – The name of the instrument to be created

      - unit (`str`) – The unit for observations this instrument reports. For example, `By` for bytes. UCUM units are recommended.

      - description (`str`) – A description for this instrument and what it measures.

    Return type:

      `Histogram`

  create_gauge(name, unit='', description='')

    Creates a `Gauge` instrument

    Parameters:

      - name – The name of the instrument to be created

      - unit – The unit for observations this instrument reports. For example, `By` for bytes. UCUM units are recommended.

      - description – A description for this instrument and what it measures.

    Return type:

      `Gauge`

  create_observable_gauge(name, callbacks=None, unit='', description='')

    Creates an `ObservableGauge` instrument

    Parameters:

      - name – The name of the instrument to be created

      - callbacks – A sequence of callbacks that return an iterable of `Observation`. Alternatively, can be a generator that yields iterables of `Observation`.

      - unit – The unit for observations this instrument reports. For example, `By` for bytes. UCUM units are recommended.

      - description – A description for this instrument and what it measures.

    Return type:

      `ObservableGauge`

  create_observable_up_down_counter(name, callbacks=None, unit='', description='')

    Creates an `ObservableUpDownCounter` instrument

    Parameters:

      - name – The name of the instrument to be created

      - callbacks – A sequence of callbacks that return an iterable of `Observation`. Alternatively, can be a generator that yields iterables of `Observation`.

      - unit – The unit for observations this instrument reports. For example, `By` for bytes. UCUM units are recommended.

      - description – A description for this instrument and what it measures.

    Return type:

      `ObservableUpDownCounter`

class opentelemetry.sdk.metrics.MeterProvider(metric_readers=(), resource=None, exemplar_filter=None, shutdown_on_exit=True, views=(), *, _meter_configurator=None)

  Bases: `MeterProvider`

  See `opentelemetry.metrics.MeterProvider`.

  Parameters:

    - metric_readers (`Sequence`[`MetricReader`]) – Register metric readers to collect metrics from the SDK on demand. Each `opentelemetry.sdk.metrics.export.MetricReader` is completely independent and will collect separate streams of metrics. For push-based export, use `opentelemetry.sdk.metrics.export.PeriodicExportingMetricReader`.

    - resource (`Resource` | `None`) – The resource representing what the metrics emitted from the SDK pertain to.

    - shutdown_on_exit (`bool`) – If true, registers an `atexit` handler to call `MeterProvider.shutdown`

    - views (`Sequence`[`View`]) – The views to configure the metric output the SDK

  Push-based export with PeriodicExportingMetricReader

      from opentelemetry.sdk.metrics import MeterProvider
      from opentelemetry.sdk.metrics.export import (
          ConsoleMetricExporter,
          PeriodicExportingMetricReader,
      )

      reader = PeriodicExportingMetricReader(ConsoleMetricExporter())
      provider = MeterProvider(metric_readers=[reader])

  By default, instruments which do not match any `opentelemetry.sdk.metrics.view.View` (or if no `opentelemetry.sdk.metrics.view.View`s are provided) will report metrics with the default aggregation for the instrument’s kind. To disable instruments by default, configure a match-all `opentelemetry.sdk.metrics.view.View` with `DropAggregation` and then create `opentelemetry.sdk.metrics.view.View`s to re-enable individual instruments:

  Disable default views

      MeterProvider(
          views=[
              View(instrument_name="*", aggregation=DropAggregation()),
              View(instrument_name="mycounter"),
          ],
          # ...
      )

  force_flush(timeout_millis=10000)
    Return type:

      `bool`

  shutdown(timeout_millis=30000)
  get_meter(name, version=None, schema_url=None, attributes=None)

    Returns a `Meter` for use by the given instrumentation library.

    For any two calls it is undefined whether the same or different `Meter` instances are returned, even for different library names.

    This function may return different `Meter` types (e.g. a no-op meter vs. a functional meter).

    Parameters:

      - name (`str`) –

        The name of the instrumenting module. `__name__` should be avoided as this can result in different meter names if the meters are in different files. It is better to use a fixed string that can be imported where needed and used consistently as the name of the meter.

        This should not be the name of the module that is instrumented but the name of the module doing the instrumentation. E.g., instead of `"requests"`, use `"opentelemetry.instrumentation.requests"`.

      - version (`str` | `None`) – Optional. The version string of the instrumenting library. Usually this should be the same as `importlib.metadata.version(instrumenting_library_name)`.

      - schema_url (`str` | `None`) – Optional. Specifies the Schema URL of the emitted telemetry.

      - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – Optional. Attributes that are associated with the emitted telemetry.

    Return type:

      `Meter`

  add_metric_reader(metric_reader)
    Return type:

      `None`

  remove_metric_reader(metric_reader)
    Return type:

      `None`

exception opentelemetry.sdk.metrics.MetricsTimeoutError

  Bases: `Exception`

  Raised when a metrics function times out

class opentelemetry.sdk.metrics.Counter(name, instrumentation_scope, measurement_consumer, unit='', description='', *, _meter_config=None)

  Bases: `_Synchronous`, `Counter`

  add(amount, attributes=None, context=None)

    Records an increment to the counter.

    Parameters:

      - amount (`int` | `float`) – The amount to increment the counter by. Must be non-negative.

      - attributes (`dict`[`str`, `str`] | `None`) – Optional set of attributes to associate with the measurement.

      - context (`Context` | `None`) – Optional context to associate with the measurement. If not provided, the current context is used.

class opentelemetry.sdk.metrics.Histogram(name, instrumentation_scope, measurement_consumer, unit='', description='', explicit_bucket_boundaries_advisory=None, *, _meter_config=None)

  Bases: `_Synchronous`, `Histogram`

  record(amount, attributes=None, context=None)

    Records a measurement.

    Used to report measurements that are likely to be statistically meaningful, such as request durations, payload sizes, or any value for which a distribution (e.g. percentiles) is useful.

    Parameters:

      - amount (`int` | `float`) – The measurement to record. Should be non-negative in most cases; negative values are only meaningful when the histogram is used to track signed deltas.

      - attributes (`dict`[`str`, `str`] | `None`) – Optional set of attributes to associate with the measurement.

      - context (`Context` | `None`) – Optional context to associate with the measurement. If not provided, the current context is used.

class opentelemetry.sdk.metrics.ObservableCounter(name, instrumentation_scope, measurement_consumer, callbacks=None, unit='', description='', *, _meter_config=None)

  Bases: `_Asynchronous`, `ObservableCounter`

class opentelemetry.sdk.metrics.ObservableGauge(name, instrumentation_scope, measurement_consumer, callbacks=None, unit='', description='', *, _meter_config=None)

  Bases: `_Asynchronous`, `ObservableGauge`

class opentelemetry.sdk.metrics.ObservableUpDownCounter(name, instrumentation_scope, measurement_consumer, callbacks=None, unit='', description='', *, _meter_config=None)

  Bases: `_Asynchronous`, `ObservableUpDownCounter`

class opentelemetry.sdk.metrics.SimpleFixedSizeExemplarReservoir(size=1, **kwargs)

  Bases: `FixedSizeExemplarReservoirABC`

  This reservoir uses an uniformly-weighted sampling algorithm based on the number of samples the reservoir has seen so far to determine if the offered measurements should be sampled.

  Reference:

    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#simplefixedsizeexemplarreservoir

class opentelemetry.sdk.metrics.UpDownCounter(name, instrumentation_scope, measurement_consumer, unit='', description='', *, _meter_config=None)

  Bases: `_Synchronous`, `UpDownCounter`

  add(amount, attributes=None, context=None)

    Records an increment or decrement to the counter.

    Unlike `Counter`, the `amount` may be negative, allowing the instrument to track values that go up and down (e.g. number of active requests, queue depth).

    Parameters:

      - amount (`int` | `float`) – The amount to add to the counter. May be positive or negative.

      - attributes (`dict`[`str`, `str`] | `None`) – Optional set of attributes to associate with the measurement.

      - context (`Context` | `None`) – Optional context to associate with the measurement. If not provided, the current context is used.

class opentelemetry.sdk.metrics.TraceBasedExemplarFilter

  Bases: `ExemplarFilter`

  An ExemplarFilter which makes those measurements eligible for being an Exemplar, which are recorded in the context of a sampled parent span.

  Reference:

    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#tracebased

  should_sample(value, time_unix_nano, attributes, context)

    Returns whether or not a reservoir should attempt to filter a measurement.

    Parameters:

      - value (`int` | `float`) – The value of the measurement

      - timestamp – A timestamp that best represents when the measurement was taken

      - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – The complete set of measurement attributes

      - context (`Context`) – The Context of the measurement

    Return type:

      `bool`