opentelemetry.metrics package

Module contents

The OpenTelemetry metrics API describes the classes used to generate metrics.

The MeterProvider provides users access to the Meter which in turn is used to create Instrument objects. The Instrument objects are used to record measurements.

This module provides abstract (i.e. unimplemented) classes required for metrics, and a concrete no-op implementation NoOpMeter that allows applications to use the API package alone without a supporting implementation.

To get a meter, you need to provide the package name from which you are calling the meter APIs to OpenTelemetry by calling MeterProvider.get_meter with the calling instrumentation name and the version of your package.

The following code shows how to obtain a meter using the global MeterProvider:

from opentelemetry.metrics import get_meter

meter = get_meter("example-meter")
counter = meter.create_counter("example-counter")

New in version 1.10.0.

Changed in version 1.12.0rc.

class opentelemetry.metrics.CallbackOptions(timeout_millis=10000)

Bases: object

Options for the callback

Parameters:

timeout_millis (float) – Timeout for the callback’s execution. If the callback does asynchronous work (e.g. HTTP requests), it should respect this timeout.

timeout_millis: float = 10000
class opentelemetry.metrics.MeterProvider

Bases: ABC

MeterProvider is the entry point of the API. It provides access to Meter instances.

abstract get_meter(name, version=None, schema_url=None, attributes=None)[source]

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__ may not be used 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 (Optional[str]) – Optional. The version string of the instrumenting library. Usually this should be the same as importlib.metadata.version(instrumenting_library_name).

  • schema_url (Optional[str]) – Optional. Specifies the Schema URL of the emitted telemetry.

  • attributes (Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]]) – Optional. Attributes that are associated with the emitted telemetry.

Return type:

Meter

class opentelemetry.metrics.NoOpMeterProvider

Bases: MeterProvider

The default MeterProvider used when no MeterProvider implementation is available.

get_meter(name, version=None, schema_url=None, attributes=None)[source]

Returns a NoOpMeter.

Return type:

Meter

class opentelemetry.metrics.Meter(name, version=None, schema_url=None)

Bases: ABC

Handles instrument creation.

This class provides methods for creating instruments which are then used to produce measurements.

abstract create_counter(name, unit='', description='')[source]

Creates a Counter 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:

Counter

create_gauge(name, unit='', description='')[source]

Creates a Gauge 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:

Gauge

abstract create_histogram(name, unit='', description='')[source]

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

abstract create_observable_counter(name, callbacks=None, unit='', description='')[source]

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:
Return type:

ObservableCounter

abstract create_observable_gauge(name, callbacks=None, unit='', description='')[source]

Creates an ObservableGauge instrument

Parameters:
Return type:

ObservableGauge

abstract create_observable_up_down_counter(name, callbacks=None, unit='', description='')[source]

Creates an ObservableUpDownCounter instrument

Parameters:
Return type:

ObservableUpDownCounter

abstract create_up_down_counter(name, unit='', description='')[source]

Creates an UpDownCounter 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:

UpDownCounter

property name: str

The name of the instrumenting module.

property schema_url: str | None

Specifies the Schema URL of the emitted telemetry

property version: str | None

The version string of the instrumenting library.

class opentelemetry.metrics.Counter(name, unit='', description='')

Bases: Synchronous

A Counter is a synchronous Instrument which supports non-negative increments.

abstract add(amount, attributes=None)[source]
Return type:

None

class opentelemetry.metrics.NoOpCounter(name, unit='', description='')

Bases: Counter

No-op implementation of Counter.

add(amount, attributes=None)[source]
Return type:

None

class opentelemetry.metrics.UpDownCounter(name, unit='', description='')

Bases: Synchronous

An UpDownCounter is a synchronous Instrument which supports increments and decrements.

abstract add(amount, attributes=None)[source]
Return type:

None

class opentelemetry.metrics.NoOpUpDownCounter(name, unit='', description='')

Bases: UpDownCounter

No-op implementation of UpDownCounter.

add(amount, attributes=None)[source]
Return type:

None

class opentelemetry.metrics.Histogram(name, unit='', description='')

Bases: Synchronous

Histogram is a synchronous Instrument which can be used to report arbitrary values that are likely to be statistically meaningful. It is intended for statistics such as histograms, summaries, and percentile.

abstract record(amount, attributes=None)[source]
Return type:

None

class opentelemetry.metrics.NoOpHistogram(name, unit='', description='')

Bases: Histogram

No-op implementation of Histogram.

record(amount, attributes=None)[source]
Return type:

None

class opentelemetry.metrics.ObservableCounter(name, callbacks=None, unit='', description='')

Bases: Asynchronous

An ObservableCounter is an asynchronous Instrument which reports monotonically increasing value(s) when the instrument is being observed.

class opentelemetry.metrics.NoOpObservableCounter(name, callbacks=None, unit='', description='')

Bases: ObservableCounter

No-op implementation of ObservableCounter.

class opentelemetry.metrics.ObservableUpDownCounter(name, callbacks=None, unit='', description='')

Bases: Asynchronous

An ObservableUpDownCounter is an asynchronous Instrument which reports additive value(s) (e.g. the process heap size - it makes sense to report the heap size from multiple processes and sum them up, so we get the total heap usage) when the instrument is being observed.

class opentelemetry.metrics.Instrument(name, unit='', description='')

Bases: ABC

Abstract class that serves as base for all instruments.

class opentelemetry.metrics.Synchronous(name, unit='', description='')

Bases: Instrument

Base class for all synchronous instruments

class opentelemetry.metrics.Asynchronous(name, callbacks=None, unit='', description='')

Bases: Instrument

Base class for all asynchronous instruments

class opentelemetry.metrics.NoOpObservableGauge(name, callbacks=None, unit='', description='')

Bases: ObservableGauge

No-op implementation of ObservableGauge.

class opentelemetry.metrics.ObservableGauge(name, callbacks=None, unit='', description='')

Bases: Asynchronous

Asynchronous Gauge is an asynchronous Instrument which reports non-additive value(s) (e.g. the room temperature - it makes no sense to report the temperature value from multiple rooms and sum them up) when the instrument is being observed.

class opentelemetry.metrics.NoOpObservableUpDownCounter(name, callbacks=None, unit='', description='')

Bases: ObservableUpDownCounter

No-op implementation of ObservableUpDownCounter.

opentelemetry.metrics.get_meter(name, version='', meter_provider=None, schema_url=None)

Returns a Meter for use by the given instrumentation library.

This function is a convenience wrapper for opentelemetry.metrics.MeterProvider.get_meter.

If meter_provider is omitted the current configured one is used.

Return type:

Meter

opentelemetry.metrics.get_meter_provider()

Gets the current global MeterProvider object.

Return type:

MeterProvider

opentelemetry.metrics.set_meter_provider(meter_provider)

Sets the current global MeterProvider object.

This can only be done once, a warning will be logged if any further attempt is made.

Return type:

None

class opentelemetry.metrics.Observation(value, attributes=None)

Bases: object

A measurement observed in an asynchronous instrument

Return/yield instances of this class from asynchronous instrument callbacks.

Parameters:
property attributes: Mapping[str, str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]] | None
property value: float | int
class opentelemetry.metrics.NoOpMeter(name, version=None, schema_url=None)

Bases: Meter

The default Meter used when no Meter implementation is available.

All operations are no-op.

create_counter(name, unit='', description='')[source]

Returns a no-op Counter.

Return type:

Counter

create_gauge(name, unit='', description='')[source]

Returns a no-op Gauge.

Return type:

Gauge

create_histogram(name, unit='', description='')[source]

Returns a no-op Histogram.

Return type:

Histogram

create_observable_counter(name, callbacks=None, unit='', description='')[source]

Returns a no-op ObservableCounter.

Return type:

ObservableCounter

create_observable_gauge(name, callbacks=None, unit='', description='')[source]

Returns a no-op ObservableGauge.

Return type:

ObservableGauge

create_observable_up_down_counter(name, callbacks=None, unit='', description='')[source]

Returns a no-op ObservableUpDownCounter.

Return type:

ObservableUpDownCounter

create_up_down_counter(name, unit='', description='')[source]

Returns a no-op UpDownCounter.

Return type:

UpDownCounter