Skip to main content

opentelemetry/metrics/instruments/
gauge.rs

1use crate::KeyValue;
2use core::fmt;
3use std::sync::Arc;
4
5#[cfg(feature = "experimental_metrics_bound_instruments")]
6use super::BoundSyncInstrument;
7use super::SyncInstrument;
8
9/// An instrument that records independent values
10///
11/// [`Gauge`] can be cloned to create multiple handles to the same instrument. If a [`Gauge`] needs to be shared,
12/// users are recommended to clone the [`Gauge`] instead of creating duplicate [`Gauge`]s for the same metric. Creating
13/// duplicate [`Gauge`]s for the same metric could lower SDK performance.
14#[derive(Clone)]
15#[non_exhaustive]
16pub struct Gauge<T>(Arc<dyn SyncInstrument<T> + Send + Sync>);
17
18impl<T> fmt::Debug for Gauge<T>
19where
20    T: fmt::Debug,
21{
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        f.write_fmt(format_args!("Gauge<{}>", std::any::type_name::<T>()))
24    }
25}
26
27impl<T> Gauge<T> {
28    /// Create a new gauge.
29    pub fn new(inner: Arc<dyn SyncInstrument<T> + Send + Sync>) -> Self {
30        Gauge(inner)
31    }
32
33    /// Records an independent value.
34    pub fn record(&self, value: T, attributes: &[KeyValue]) {
35        self.0.measure(value, attributes)
36    }
37
38    /// Binds this gauge to a fixed set of attributes.
39    ///
40    /// Corresponds to the `Bind` capability in the OpenTelemetry spec (status:
41    /// Development as of spec 1.57.0).
42    #[cfg(feature = "experimental_metrics_bound_instruments")]
43    pub fn bind(&self, attributes: &[KeyValue]) -> BoundGauge<T> {
44        BoundGauge(Arc::from(self.0.bind(attributes)))
45    }
46}
47
48/// A gauge bound to a fixed set of attributes.
49///
50/// Created by calling [`Gauge::bind`] with an attribute set. All subsequent
51/// [`record`](BoundGauge::record) calls use the pre-resolved attributes, bypassing
52/// per-call attribute lookup for significantly better performance.
53///
54/// `BoundGauge` can be cloned cheaply to share a single bound state across
55/// threads or modules without re-binding. The underlying tracker is reclaimed
56/// when the last clone is dropped.
57#[cfg(feature = "experimental_metrics_bound_instruments")]
58#[derive(Clone)]
59#[must_use = "dropping a BoundGauge immediately is a no-op; store it to benefit from pre-bound attributes"]
60pub struct BoundGauge<T>(Arc<dyn BoundSyncInstrument<T> + Send + Sync>);
61
62#[cfg(feature = "experimental_metrics_bound_instruments")]
63impl<T> fmt::Debug for BoundGauge<T> {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.write_fmt(format_args!("BoundGauge<{}>", std::any::type_name::<T>()))
66    }
67}
68
69#[cfg(feature = "experimental_metrics_bound_instruments")]
70impl<T> BoundGauge<T> {
71    /// Records an independent value using the pre-bound attributes.
72    pub fn record(&self, value: T) {
73        self.0.measure(value)
74    }
75}
76
77/// An async instrument that records independent readings.
78#[derive(Clone)]
79#[non_exhaustive]
80pub struct ObservableGauge<T> {
81    _marker: std::marker::PhantomData<T>,
82}
83
84impl<T> fmt::Debug for ObservableGauge<T>
85where
86    T: fmt::Debug,
87{
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.write_fmt(format_args!(
90            "ObservableGauge<{}>",
91            std::any::type_name::<T>()
92        ))
93    }
94}
95
96impl<T> ObservableGauge<T> {
97    /// Create a new gauge
98    #[allow(clippy::new_without_default)]
99    pub fn new() -> Self {
100        ObservableGauge {
101            _marker: std::marker::PhantomData,
102        }
103    }
104}