Skip to main content

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