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")]
43 pub fn bind(&self, attributes: &[KeyValue]) -> BoundCounter<T> {
44 BoundCounter(Arc::from(self.0.bind(attributes)))
45 }
46}
47
48#[derive(Clone)]
50#[non_exhaustive]
51pub struct ObservableCounter<T> {
52 _marker: std::marker::PhantomData<T>,
53}
54
55impl<T> ObservableCounter<T> {
56 #[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#[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 pub fn add(&self, value: T) {
99 self.0.measure(value)
100 }
101}