Skip to main content

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