opentelemetry/metrics/instruments/
counter.rs1use 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#[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 pub fn new(inner: Arc<dyn SyncInstrument<T> + Send + Sync>) -> Self {
30 Counter(inner)
31 }
32
33 pub fn add(&self, value: T, attributes: &[KeyValue]) {
35 self.0.measure(value, attributes)
36 }
37
38 #[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#[derive(Clone)]
47#[non_exhaustive]
48pub struct ObservableCounter<T> {
49 _marker: std::marker::PhantomData<T>,
50}
51
52impl<T> ObservableCounter<T> {
53 #[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#[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 pub fn add(&self, value: T) {
96 self.0.measure(value)
97 }
98}