opentelemetry.sdk.metrics package

Submodules

class opentelemetry.sdk.metrics.Meter(instrumentation_scope, measurement_consumer)

Bases: opentelemetry.metrics.Meter

See opentelemetry.metrics.Meter.

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

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_histogram(name, unit='', description='')[source]

Creates a Histogram 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

Histogram

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
  • 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_observable_gauge(name, callbacks=None, unit='', description='')[source]

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='')[source]

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

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

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

class opentelemetry.sdk.metrics.MeterProvider(metric_readers=(), resource=<opentelemetry.sdk.resources.Resource object>, shutdown_on_exit=True, views=())

Bases: opentelemetry.metrics.MeterProvider

See opentelemetry.metrics.MeterProvider.

Parameters
  • metric_readers – 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. TODO: reference PeriodicExportingMetricReader usage with push exporters here.

  • resource – The resource representing what the metrics emitted from the SDK pertain to.

  • shutdown_on_exit – If true, registers an atexit handler to call MeterProvider.shutdown

  • views – The views to configure the metric output the SDK

By default, instruments which do not match any opentelemetry.sdk.metrics.view.View (or if no opentelemetry.sdk.metrics.view.Views 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.Views to re-enable individual instruments:

Disable default views
MeterProvider(
    views=[
        View(instrument_name="*", aggregation=DropAggregation()),
        View(instrument_name="mycounter"),
    ],
    # ...
)
force_flush(timeout_millis=10000)[source]
Return type

bool

get_meter(name, version=None, schema_url=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 pkg_resources.get_distribution(instrumenting_library_name).version.

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

Return type

Meter

shutdown(timeout_millis=30000)[source]
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='')

Bases: opentelemetry.sdk.metrics._internal.instrument._Synchronous, opentelemetry.metrics.Counter

add(amount, attributes=None)[source]
class opentelemetry.sdk.metrics.Histogram(*args, **kwargs)

Bases: opentelemetry.sdk.metrics._internal.instrument._Synchronous, opentelemetry.metrics.Histogram

record(amount, attributes=None)[source]
class opentelemetry.sdk.metrics.ObservableCounter(name, instrumentation_scope, measurement_consumer, callbacks=None, unit='', description='')

Bases: opentelemetry.sdk.metrics._internal.instrument._Asynchronous, opentelemetry.metrics.ObservableCounter

class opentelemetry.sdk.metrics.ObservableGauge(*args, **kwargs)

Bases: opentelemetry.sdk.metrics._internal.instrument._Asynchronous, opentelemetry.metrics.ObservableGauge

class opentelemetry.sdk.metrics.ObservableUpDownCounter(*args, **kwargs)

Bases: opentelemetry.sdk.metrics._internal.instrument._Asynchronous, opentelemetry.metrics.ObservableUpDownCounter

class opentelemetry.sdk.metrics.UpDownCounter(*args, **kwargs)

Bases: opentelemetry.sdk.metrics._internal.instrument._Synchronous, opentelemetry.metrics.UpDownCounter

add(amount, attributes=None)[source]