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    ///
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]) -> BoundCounter<T> {
44        BoundCounter(Arc::from(self.0.bind(attributes)))
45    }
46}
47
48/// An async instrument that records increasing values.
49#[derive(Clone)]
50#[non_exhaustive]
51pub struct ObservableCounter<T> {
52    _marker: std::marker::PhantomData<T>,
53}
54
55impl<T> ObservableCounter<T> {
56    /// Create a new observable counter.
57    #[allow(clippy::new_without_default)]
58    pub fn new() -> Self {
59        ObservableCounter {
60            _marker: std::marker::PhantomData,
61        }
62    }
63}
64
65impl<T> fmt::Debug for ObservableCounter<T> {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_fmt(format_args!(
68            "ObservableCounter<{}>",
69            std::any::type_name::<T>()
70        ))
71    }
72}
73
74/// A counter bound to a fixed set of attributes.
75///
76/// Created by calling [`Counter::bind`] with an attribute set. All subsequent
77/// [`add`](BoundCounter::add) calls use the pre-resolved attributes, bypassing
78/// per-call attribute lookup for significantly better performance.
79///
80/// `BoundCounter` can be cloned cheaply to share a single bound state across
81/// threads or modules without re-binding. The underlying tracker is reclaimed
82/// when the last clone is dropped.
83#[cfg(feature = "experimental_metrics_bound_instruments")]
84#[derive(Clone)]
85#[must_use = "dropping a BoundCounter immediately is a no-op; store it to benefit from pre-bound attributes"]
86pub struct BoundCounter<T>(Arc<dyn BoundSyncInstrument<T> + Send + Sync>);
87
88#[cfg(feature = "experimental_metrics_bound_instruments")]
89impl<T> fmt::Debug for BoundCounter<T> {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_fmt(format_args!("BoundCounter<{}>", std::any::type_name::<T>()))
92    }
93}
94
95#[cfg(feature = "experimental_metrics_bound_instruments")]
96impl<T> BoundCounter<T> {
97    /// Records an increment to the counter using the pre-bound attributes.
98    pub fn add(&self, value: T) {
99        self.0.measure(value)
100    }
101}