opentelemetry/metrics/instruments/
up_down_counter.rs

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