opentelemetry/metrics/instruments/
counter.rs

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