opentelemetry/metrics/instruments/
gauge.rs

1use crate::KeyValue;
2use core::fmt;
3use std::sync::Arc;
4
5use super::SyncInstrument;
6
7/// An instrument that records independent values
8///
9/// [`Gauge`] can be cloned to create multiple handles to the same instrument. If a [`Gauge`] needs to be shared,
10/// users are recommended to clone the [`Gauge`] instead of creating duplicate [`Gauge`]s for the same metric. Creating
11/// duplicate [`Gauge`]s for the same metric could lower SDK performance.
12#[derive(Clone)]
13#[non_exhaustive]
14pub struct Gauge<T>(Arc<dyn SyncInstrument<T> + Send + Sync>);
15
16impl<T> fmt::Debug for Gauge<T>
17where
18    T: fmt::Debug,
19{
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        f.write_fmt(format_args!("Gauge<{}>", std::any::type_name::<T>()))
22    }
23}
24
25impl<T> Gauge<T> {
26    /// Create a new gauge.
27    pub fn new(inner: Arc<dyn SyncInstrument<T> + Send + Sync>) -> Self {
28        Gauge(inner)
29    }
30
31    /// Records an independent value.
32    pub fn record(&self, value: T, attributes: &[KeyValue]) {
33        self.0.measure(value, attributes)
34    }
35}
36
37/// An async instrument that records independent readings.
38#[derive(Clone)]
39#[non_exhaustive]
40pub struct ObservableGauge<T> {
41    _marker: std::marker::PhantomData<T>,
42}
43
44impl<T> fmt::Debug for ObservableGauge<T>
45where
46    T: fmt::Debug,
47{
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.write_fmt(format_args!(
50            "ObservableGauge<{}>",
51            std::any::type_name::<T>()
52        ))
53    }
54}
55
56impl<T> ObservableGauge<T> {
57    /// Create a new gauge
58    #[allow(clippy::new_without_default)]
59    pub fn new() -> Self {
60        ObservableGauge {
61            _marker: std::marker::PhantomData,
62        }
63    }
64}