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")
Added in version 1.10.0.
Changed in version 1.12.0rc.
- class opentelemetry.metrics.CallbackOptions(timeout_millis=10000)
Bases:
objectOptions 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:
ABCMeterProvider is the entry point of the API. It provides access to
Meterinstances.- abstractmethod get_meter(name, version=None, schema_url=None, attributes=None)[source]
Returns a
Meterfor use by the given instrumentation library.For any two calls it is undefined whether the same or different
Meterinstances are returned, even for different library names.This function may return different
Metertypes (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 (
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.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:
- class opentelemetry.metrics.NoOpMeterProvider
Bases:
MeterProviderThe default MeterProvider used when no MeterProvider implementation is available.
- class opentelemetry.metrics.Meter(name, version=None, schema_url=None)
Bases:
ABCHandles instrument creation.
This class provides methods for creating instruments which are then used to produce measurements.
- abstractmethod create_histogram(name, unit='', description='', *, explicit_bucket_boundaries_advisory=None)[source]
Creates a
Histograminstrument
- abstractmethod create_observable_counter(name, callbacks=None, unit='', description='')[source]
Creates an
ObservableCounterinstrumentAn observable counter observes a monotonically increasing count by calling provided callbacks which accept a
CallbackOptionsand 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
CallbackOptionscontain 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,Byfor bytes. UCUM units are recommended.description (
str) – A description for this instrument and what it measures.
- Return type:
- abstractmethod create_observable_gauge(name, callbacks=None, unit='', description='')[source]
Creates an
ObservableGaugeinstrument- 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,Byfor bytes. UCUM units are recommended.description (
str) – A description for this instrument and what it measures.
- Return type:
- abstractmethod create_observable_up_down_counter(name, callbacks=None, unit='', description='')[source]
Creates an
ObservableUpDownCounterinstrument- 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,Byfor bytes. UCUM units are recommended.description (
str) – A description for this instrument and what it measures.
- Return type:
- abstractmethod create_up_down_counter(name, unit='', description='')[source]
Creates an
UpDownCounterinstrument- Parameters:
- Return type:
- class opentelemetry.metrics.Counter(name, unit='', description='')
Bases:
SynchronousA Counter is a synchronous
Instrumentwhich supports non-negative increments.- abstractmethod add(amount, attributes=None, context=None)[source]
Records an increment to the counter.
- Parameters:
amount (
Union[int,float]) – The amount to increment the counter by. Must be non-negative.attributes (
Optional[Mapping[str,Union[str,bool,int,float,Sequence[str],Sequence[bool],Sequence[int],Sequence[float]]]]) – Optional set of attributes to associate with the measurement.context (
Optional[Context]) – Optional context to associate with the measurement. If not provided, the current context is used.
- Return type:
- class opentelemetry.metrics.NoOpCounter(name, unit='', description='')
Bases:
CounterNo-op implementation of
Counter.- add(amount, attributes=None, context=None)[source]
Records an increment to the counter.
- Parameters:
amount (
Union[int,float]) – The amount to increment the counter by. Must be non-negative.attributes (
Optional[Mapping[str,Union[str,bool,int,float,Sequence[str],Sequence[bool],Sequence[int],Sequence[float]]]]) – Optional set of attributes to associate with the measurement.context (
Optional[Context]) – Optional context to associate with the measurement. If not provided, the current context is used.
- Return type:
- class opentelemetry.metrics.UpDownCounter(name, unit='', description='')
Bases:
SynchronousAn UpDownCounter is a synchronous
Instrumentwhich supports increments and decrements.- abstractmethod add(amount, attributes=None, context=None)[source]
Records an increment or decrement to the counter.
Unlike
Counter, theamountmay be negative, allowing the instrument to track values that go up and down (e.g. number of active requests, queue depth).- Parameters:
amount (
Union[int,float]) – The amount to add to the counter. May be positive or negative.attributes (
Optional[Mapping[str,Union[str,bool,int,float,Sequence[str],Sequence[bool],Sequence[int],Sequence[float]]]]) – Optional set of attributes to associate with the measurement.context (
Optional[Context]) – Optional context to associate with the measurement. If not provided, the current context is used.
- Return type:
- class opentelemetry.metrics.NoOpUpDownCounter(name, unit='', description='')
Bases:
UpDownCounterNo-op implementation of
UpDownCounter.- add(amount, attributes=None, context=None)[source]
Records an increment or decrement to the counter.
Unlike
Counter, theamountmay be negative, allowing the instrument to track values that go up and down (e.g. number of active requests, queue depth).- Parameters:
amount (
Union[int,float]) – The amount to add to the counter. May be positive or negative.attributes (
Optional[Mapping[str,Union[str,bool,int,float,Sequence[str],Sequence[bool],Sequence[int],Sequence[float]]]]) – Optional set of attributes to associate with the measurement.context (
Optional[Context]) – Optional context to associate with the measurement. If not provided, the current context is used.
- Return type:
- class opentelemetry.metrics.Histogram(name, unit='', description='', explicit_bucket_boundaries_advisory=None)
Bases:
SynchronousHistogram is a synchronous
Instrumentwhich 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.- abstractmethod record(amount, attributes=None, context=None)[source]
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 (
Union[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 (
Optional[Mapping[str,Union[str,bool,int,float,Sequence[str],Sequence[bool],Sequence[int],Sequence[float]]]]) – Optional set of attributes to associate with the measurement.context (
Optional[Context]) – Optional context to associate with the measurement. If not provided, the current context is used.
- Return type:
- class opentelemetry.metrics.NoOpHistogram(name, unit='', description='', explicit_bucket_boundaries_advisory=None)
Bases:
HistogramNo-op implementation of
Histogram.- record(amount, attributes=None, context=None)[source]
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 (
Union[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 (
Optional[Mapping[str,Union[str,bool,int,float,Sequence[str],Sequence[bool],Sequence[int],Sequence[float]]]]) – Optional set of attributes to associate with the measurement.context (
Optional[Context]) – Optional context to associate with the measurement. If not provided, the current context is used.
- Return type:
- class opentelemetry.metrics.ObservableCounter(name, callbacks=None, unit='', description='')
Bases:
AsynchronousAn ObservableCounter is an asynchronous
Instrumentwhich reports monotonically increasing value(s) when the instrument is being observed.
- class opentelemetry.metrics.NoOpObservableCounter(name, callbacks=None, unit='', description='')
Bases:
ObservableCounterNo-op implementation of
ObservableCounter.
- class opentelemetry.metrics.ObservableUpDownCounter(name, callbacks=None, unit='', description='')
Bases:
AsynchronousAn ObservableUpDownCounter is an asynchronous
Instrumentwhich 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:
ABCAbstract class that serves as base for all instruments.
- class opentelemetry.metrics.Synchronous(name, unit='', description='')
Bases:
InstrumentBase class for all synchronous instruments
- class opentelemetry.metrics.Asynchronous(name, callbacks=None, unit='', description='')
Bases:
InstrumentBase class for all asynchronous instruments
- class opentelemetry.metrics.NoOpObservableGauge(name, callbacks=None, unit='', description='')
Bases:
ObservableGaugeNo-op implementation of
ObservableGauge.
- class opentelemetry.metrics.ObservableGauge(name, callbacks=None, unit='', description='')
Bases:
AsynchronousAsynchronous Gauge is an asynchronous
Instrumentwhich 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:
ObservableUpDownCounterNo-op implementation of
ObservableUpDownCounter.
- opentelemetry.metrics.get_meter(name, version='', meter_provider=None, schema_url=None, attributes=None)
Returns a
Meterfor 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
MeterProviderobject.- Return type:
- opentelemetry.metrics.set_meter_provider(meter_provider)
Sets the current global
MeterProviderobject.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, context=None)
Bases:
objectA measurement observed in an asynchronous instrument
Return/yield instances of this class from asynchronous instrument callbacks.
- Parameters:
- class opentelemetry.metrics.NoOpMeter(name, version=None, schema_url=None)
Bases:
MeterThe default Meter used when no Meter implementation is available.
All operations are no-op.
- create_histogram(name, unit='', description='', *, explicit_bucket_boundaries_advisory=None)[source]
Returns a no-op Histogram.
- Return type:
- 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: