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.
-
class
opentelemetry.metrics.
MeterProvider
¶ Bases:
abc.ABC
MeterProvider is the entry point of the API. It provides access to
Meter
instances.-
abstract
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 asimportlib.metadata.version(instrumenting_library_name)
.schema_url (
Optional
[str
]) – Optional. Specifies the Schema URL of the emitted telemetry.
- Return type
-
abstract
-
class
opentelemetry.metrics.
NoOpMeterProvider
¶ Bases:
opentelemetry.metrics.MeterProvider
The default MeterProvider used when no MeterProvider implementation is available.
-
class
opentelemetry.metrics.
Meter
(name, version=None, schema_url=None)¶ Bases:
abc.ABC
Handles instrument creation.
This class provides methods for creating instruments which are then used to produce measurements.
-
abstract
create_observable_counter
(name, callbacks=None, unit='', description='')[source]¶ Creates an
ObservableCounter
instrumentAn observable counter observes a monotonically increasing count by calling provided callbacks which accept a
CallbackOptions
and return multipleObservation
.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 (
str
) – The name of the instrument to be createdcallbacks (
Optional
[Sequence
[Union
[Callable
[[CallbackOptions
],Iterable
[Observation
]],Generator
[Iterable
[Observation
],CallbackOptions
,None
]]]]) – A sequence of callbacks that return an iterable ofObservation
. Alternatively, can be a sequence of generators that each yields iterables ofObservation
.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
-
abstract
create_observable_gauge
(name, callbacks=None, unit='', description='')[source]¶ Creates an
ObservableGauge
instrument- Parameters
name (
str
) – The name of the instrument to be createdcallbacks (
Optional
[Sequence
[Union
[Callable
[[CallbackOptions
],Iterable
[Observation
]],Generator
[Iterable
[Observation
],CallbackOptions
,None
]]]]) – A sequence of callbacks that return an iterable ofObservation
. Alternatively, can be a generator that yields iterables ofObservation
.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
-
abstract
create_observable_up_down_counter
(name, callbacks=None, unit='', description='')[source]¶ Creates an
ObservableUpDownCounter
instrument- Parameters
name (
str
) – The name of the instrument to be createdcallbacks (
Optional
[Sequence
[Union
[Callable
[[CallbackOptions
],Iterable
[Observation
]],Generator
[Iterable
[Observation
],CallbackOptions
,None
]]]]) – A sequence of callbacks that return an iterable ofObservation
. Alternatively, can be a generator that yields iterables ofObservation
.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
-
abstract
create_up_down_counter
(name, unit='', description='')[source]¶ Creates an
UpDownCounter
instrument- Parameters
- Return type
-
abstract
-
class
opentelemetry.metrics.
Counter
(name, unit='', description='')¶ Bases:
opentelemetry.metrics.Synchronous
A Counter is a synchronous
Instrument
which supports non-negative increments.
-
class
opentelemetry.metrics.
NoOpCounter
(name, unit='', description='')¶ Bases:
opentelemetry.metrics.Counter
No-op implementation of
Counter
.
-
class
opentelemetry.metrics.
UpDownCounter
(name, unit='', description='')¶ Bases:
opentelemetry.metrics.Synchronous
An UpDownCounter is a synchronous
Instrument
which supports increments and decrements.
-
class
opentelemetry.metrics.
NoOpUpDownCounter
(name, unit='', description='')¶ Bases:
opentelemetry.metrics.UpDownCounter
No-op implementation of
UpDownCounter
.
-
class
opentelemetry.metrics.
Histogram
(name, unit='', description='')¶ Bases:
opentelemetry.metrics.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.
-
class
opentelemetry.metrics.
NoOpHistogram
(name, unit='', description='')¶ Bases:
opentelemetry.metrics.Histogram
No-op implementation of
Histogram
.
-
class
opentelemetry.metrics.
ObservableCounter
(name, callbacks=None, unit='', description='')¶ Bases:
opentelemetry.metrics.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:
opentelemetry.metrics.ObservableCounter
No-op implementation of
ObservableCounter
.
-
class
opentelemetry.metrics.
ObservableUpDownCounter
(name, callbacks=None, unit='', description='')¶ Bases:
opentelemetry.metrics.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.ABC
Abstract class that serves as base for all instruments.
-
class
opentelemetry.metrics.
Synchronous
(name, unit='', description='')¶ Bases:
opentelemetry.metrics.Instrument
Base class for all synchronous instruments
-
class
opentelemetry.metrics.
Asynchronous
(name, callbacks=None, unit='', description='')¶ Bases:
opentelemetry.metrics.Instrument
Base class for all asynchronous instruments
-
class
opentelemetry.metrics.
NoOpObservableGauge
(name, callbacks=None, unit='', description='')¶ Bases:
opentelemetry.metrics.ObservableGauge
No-op implementation of
ObservableGauge
.
-
class
opentelemetry.metrics.
ObservableGauge
(name, callbacks=None, unit='', description='')¶ Bases:
opentelemetry.metrics.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:
opentelemetry.metrics.ObservableUpDownCounter
No-op implementation of
ObservableUpDownCounter
.
-
opentelemetry.metrics.
get_meter
(name, version='', meter_provider=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
-
opentelemetry.metrics.
get_meter_provider
()¶ Gets the current global
MeterProvider
object.- Return type
-
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
-
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
¶
-
class
opentelemetry.metrics.
NoOpMeter
(name, version=None, schema_url=None)¶ Bases:
opentelemetry.metrics.Meter
The default Meter used when no Meter implementation is available.
All operations are no-op.
-
create_observable_counter
(name, callbacks=None, unit='', description='')[source]¶ Returns a no-op ObservableCounter.
- Return type
-
create_observable_gauge
(name, callbacks=None, unit='', description='')[source]¶ Returns a no-op ObservableGauge.
- Return type
-
create_observable_up_down_counter
(name, callbacks=None, unit='', description='')[source]¶ Returns a no-op ObservableUpDownCounter.
- Return type
-