Skip to main content

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