Skip to main content

encore/
metrics.rs

1//! Metrics: counters, gauges and histograms of what an app does.
2//!
3//! A metric is declared as a `static` and used wherever the thing it measures
4//! happens. Its doc comment is its description:
5//!
6//! ```ignore
7//! use encore::metrics::{Counter, Gauge, Histogram, UpDownCounter};
8//!
9//! /// Orders placed.
10//! static ORDERS: Counter = Counter::new("orders_placed");
11//!
12//! /// Jobs waiting for a worker.
13//! static QUEUED: UpDownCounter = UpDownCounter::new("jobs_queued").unit("{job}");
14//!
15//! /// The temperature of the oven.
16//! static OVEN: Gauge = Gauge::new("oven_temperature").unit("Cel");
17//!
18//! /// How long an order takes to place.
19//! static LATENCY: Histogram = Histogram::new("order_latency").unit("s");
20//!
21//! ORDERS.increment();
22//! QUEUED.add(12);
23//! OVEN.set(180.5);
24//! LATENCY.record(started.elapsed().as_secs_f64());
25//! ```
26//!
27//! Each is an instrument of the [OpenTelemetry Metrics API](crate::opentelemetry::metrics),
28//! of the meter `encore`, named as declared, a service's own prefixed with
29//! its service's name (`orders_placed` of the service `shop` is exported as
30//! `shop.orders_placed`), created when it is first recorded to. Its data is
31//! exported with the rest of the app's: the process's resource names the
32//! service recording it. Instruments of the API itself made with Encore's
33//! [meter provider](meter_provider) are exported alongside: observable
34//! instruments are made with it. Encore installs no global meter provider:
35//!
36//! ```ignore
37//! encore::opentelemetry::global::set_meter_provider(encore::metrics::meter_provider());
38//! ```
39//!
40//! | Metric | What it is | Values |
41//! |---|---|---|
42//! | [`Counter`] | a total that only goes up | `u64`, `f64` |
43//! | [`UpDownCounter`] | a total that goes up and down | `i64`, `f64` |
44//! | [`Gauge`] | what something is right now | `f64`, `i64`, `u64` |
45//! | [`Histogram`] | how values are distributed | `f64` |
46//!
47//! The first type in each list is the default. A unit is given as it is to be
48//! exported: [UCUM](https://ucum.org/ucum) is the convention (`"s"`, `"By"`,
49//! `"{request}"`). A description given with `.description(…)`, where there is
50//! no doc comment, is the instrument's too.
51//!
52//! # Scope
53//!
54//! Which type a metric is declared with says who records to it, as with
55//! [secrets](crate::secrets#scope):
56//!
57//! - A [`Counter`], [`Gauge`], … belongs to the service that declares it, and
58//!   only that service records to it. Its name is unique in the service: two
59//!   services may each declare a `requests` counter, exported as
60//!   `<service>.requests`. It must be declared inside a service.
61//! - A [`SharedCounter`], [`SharedGauge`], … is shared between services, under
62//!   one name in the app. Each service that records to it is recorded as using
63//!   it.
64//! - A [`GlobalCounter`], [`GlobalGauge`], … is the whole app's. Any code may
65//!   record to it — a library outside every service too — and who does is not
66//!   recorded.
67//!
68//! The groups, below, come in the same three.
69//!
70//! A shared or global metric is declared once in the app, as a [shared
71//! secret](crate::secrets#scope) is. Other code records to it by importing
72//! the declaration, or, from another service's crate or another language, by
73//! binding it by name:
74//!
75//! ```ignore
76//! static SERVED: CounterGroup<Served> = CounterGroup::named("greetings.served");
77//! ```
78//!
79//! A named metric is of the declaration's kind and labels, and takes its
80//! scope, unit, description and buckets; it is exported under the name as
81//! written, never prefixed with a service's. To hand a metric to other code,
82//! pass [`reference()`](Counter::reference): it counts as recording to it.
83//!
84//! # Labels
85//!
86//! A metric that is one number is a [`Counter`], [`Gauge`], … A *group* —
87//! [`CounterGroup`], [`GaugeGroup`], … — is one number for each combination of
88//! its labels, which are the fields of a struct, each an attribute of what is
89//! recorded:
90//!
91//! ```ignore
92//! use encore::metrics::{CounterGroup, Labels};
93//!
94//! #[derive(Labels)]
95//! struct Outcome {
96//!     method: &'static str,
97//!     status: u16,
98//! }
99//!
100//! /// Requests handled, by method and status.
101//! static REQUESTS: CounterGroup<Outcome> = CounterGroup::new("requests_handled");
102//!
103//! REQUESTS.with(&Outcome { method: "GET", status: 200 }).increment();
104//! ```
105//!
106//! Every distinct combination is a time series of its own: a label is for a
107//! handful of values — a status, a region — and not for a user id. For
108//! attributes of any other shape, record with the OpenTelemetry API.
109//!
110//! # Histograms
111//!
112//! A [`Histogram`] counts what it records in buckets, to say how it is
113//! distributed: the median latency, the 99th percentile. Its
114//! [`buckets`](Histogram::buckets) are part of its definition, exported as
115//! they are declared.
116//!
117//! # Under test
118//!
119//! Under `encore test`, as wherever the runtime exports no metrics, metrics
120//! record nothing.
121
122use std::marker::PhantomData;
123use std::sync::{Arc, OnceLock};
124
125use crate::opentelemetry::metrics::{self as otel, Meter, MeterProvider as _};
126use crate::opentelemetry::{InstrumentationScope, KeyValue, Value};
127use encore_sdk_core::telemetry::MeterProvider as CoreMeterProvider;
128
129use sealed::Declaration;
130
131/// Derives [`Labels`] for a struct with named fields: each field is a label,
132/// named as the field is, whose type is a [`LabelValue`].
133pub use encore_macros::Labels;
134
135/// Encore's meter provider, an OpenTelemetry
136/// [`MeterProvider`](otel::MeterProvider), which Encore metrics record
137/// through. Cheap to clone.
138#[derive(Debug, Clone)]
139pub struct MeterProvider(Option<CoreMeterProvider>);
140
141impl otel::MeterProvider for MeterProvider {
142    fn meter_with_scope(&self, scope: InstrumentationScope) -> Meter {
143        match &self.0 {
144            Some(provider) => provider.meter_with_scope(scope),
145            None => Meter::new(Arc::new(NoInstruments)),
146        }
147    }
148}
149
150/// Makes instruments recording nothing.
151struct NoInstruments;
152
153impl otel::InstrumentProvider for NoInstruments {}
154
155impl MeterProvider {
156    /// Over `provider`, the runtime's; for none, recording nothing.
157    fn of(provider: Option<&CoreMeterProvider>) -> Self {
158        MeterProvider(provider.cloned())
159    }
160
161    /// Whether measurements are aggregated.
162    #[cfg(test)]
163    fn aggregates(&self) -> bool {
164        self.0.is_some()
165    }
166}
167
168/// Encore's meter provider: the runtime's, or, when the runtime exports no
169/// metrics, one recording nothing.
170pub fn meter_provider() -> MeterProvider {
171    MeterProvider::of(provider())
172}
173
174/// The meter every metric is an instrument of: `encore`, of this SDK's
175/// version, from Encore's meter provider.
176fn meter() -> Meter {
177    meter_provider().meter_with_scope(
178        InstrumentationScope::builder("encore")
179            .with_version(env!("CARGO_PKG_VERSION"))
180            .build(),
181    )
182}
183
184/// The runtime's meter provider; none when the runtime exports no metrics.
185#[cfg(not(test))]
186fn provider() -> Option<&'static CoreMeterProvider> {
187    crate::runtime::core().resources().meter_provider()
188}
189
190// This crate's own tests run without a runtime.
191#[cfg(test)]
192fn provider() -> Option<&'static CoreMeterProvider> {
193    Some(tests::provider())
194}
195
196/// The service this process hosts, if any.
197#[cfg(not(test))]
198fn hosted_service() -> Option<&'static str> {
199    crate::runtime::core()
200        .runtime_config()
201        .current_service
202        .as_deref()
203}
204
205// This crate's own tests host `svc`.
206#[cfg(test)]
207fn hosted_service() -> Option<&'static str> {
208    Some("svc")
209}
210
211/// What a metric's value types make its instruments with, and its
212/// declaration: neither nameable outside this module.
213mod sealed {
214    use std::borrow::Cow;
215
216    use super::{hosted_service, otel, Meter};
217
218    /// What a metric is declared with.
219    #[derive(Debug, Clone, Copy)]
220    pub struct Declaration {
221        pub(super) name: &'static str,
222        /// The declaring service's alone, exported as `<service>.<name>`.
223        pub(super) own: bool,
224        pub(super) unit: Option<&'static str>,
225        pub(super) description: Option<&'static str>,
226        pub(super) buckets: Option<&'static [f64]>,
227    }
228
229    impl Declaration {
230        pub(super) const fn new(name: &'static str, own: bool) -> Self {
231            Self {
232                name,
233                own,
234                unit: None,
235                description: None,
236                buckets: None,
237            }
238        }
239
240        /// The instrument name: a service's own metric's is
241        /// `<service>.<name>`, of the service this process hosts.
242        pub(super) fn exported_name(&self) -> Cow<'static, str> {
243            match hosted_service() {
244                Some(service) if self.own => format!("{service}.{}", self.name).into(),
245                _ => self.name.into(),
246            }
247        }
248    }
249
250    pub trait Counter: Sized {
251        const ONE: Self;
252        fn counter(meter: &Meter, declaration: &Declaration) -> otel::Counter<Self>;
253    }
254
255    pub trait UpDownCounter: Sized {
256        const ONE: Self;
257        fn up_down_counter(meter: &Meter, declaration: &Declaration) -> otel::UpDownCounter<Self>;
258    }
259
260    pub trait Gauge: Sized {
261        fn gauge(meter: &Meter, declaration: &Declaration) -> otel::Gauge<Self>;
262    }
263
264    pub trait Histogram: Sized {
265        fn histogram(meter: &Meter, declaration: &Declaration) -> otel::Histogram<Self>;
266    }
267}
268
269/// An instrument builder with a declaration's unit and description.
270macro_rules! describe {
271    ($builder:expr, $declaration:expr) => {{
272        let mut builder = $builder;
273        if let Some(unit) = $declaration.unit {
274            builder = builder.with_unit(unit);
275        }
276        if let Some(description) = $declaration.description {
277            builder = builder.with_description(description);
278        }
279        builder
280    }};
281}
282
283/// What a [`Counter`] counts in: `u64`, or `f64` for amounts that are not
284/// whole.
285pub trait CounterValue: sealed::Counter + Copy + Send + Sync + 'static {}
286
287/// What an [`UpDownCounter`] counts in: `i64`, or `f64` for amounts that are
288/// not whole.
289pub trait UpDownCounterValue:
290    sealed::UpDownCounter + Copy + std::ops::Neg<Output = Self> + Send + Sync + 'static
291{
292}
293
294/// What a [`Gauge`] holds: `f64`, `i64` or `u64`.
295pub trait GaugeValue: sealed::Gauge + Copy + Send + Sync + 'static {}
296
297/// What a [`Histogram`] records: `f64`.
298pub trait HistogramValue: sealed::Histogram + Copy + Send + Sync + 'static {}
299
300macro_rules! counter_value {
301    ($ty:ty, $one:expr, $counter:ident) => {
302        impl CounterValue for $ty {}
303
304        impl sealed::Counter for $ty {
305            const ONE: Self = $one;
306
307            fn counter(meter: &Meter, declaration: &Declaration) -> otel::Counter<Self> {
308                describe!(meter.$counter(declaration.exported_name()), declaration).build()
309            }
310        }
311    };
312}
313counter_value!(u64, 1, u64_counter);
314counter_value!(f64, 1.0, f64_counter);
315
316macro_rules! up_down_counter_value {
317    ($ty:ty, $one:expr, $counter:ident) => {
318        impl UpDownCounterValue for $ty {}
319
320        impl sealed::UpDownCounter for $ty {
321            const ONE: Self = $one;
322
323            fn up_down_counter(
324                meter: &Meter,
325                declaration: &Declaration,
326            ) -> otel::UpDownCounter<Self> {
327                describe!(meter.$counter(declaration.exported_name()), declaration).build()
328            }
329        }
330    };
331}
332up_down_counter_value!(i64, 1, i64_up_down_counter);
333up_down_counter_value!(f64, 1.0, f64_up_down_counter);
334
335macro_rules! gauge_value {
336    ($ty:ty, $gauge:ident) => {
337        impl GaugeValue for $ty {}
338
339        impl sealed::Gauge for $ty {
340            fn gauge(meter: &Meter, declaration: &Declaration) -> otel::Gauge<Self> {
341                describe!(meter.$gauge(declaration.exported_name()), declaration).build()
342            }
343        }
344    };
345}
346gauge_value!(f64, f64_gauge);
347gauge_value!(i64, i64_gauge);
348gauge_value!(u64, u64_gauge);
349
350impl HistogramValue for f64 {}
351
352impl sealed::Histogram for f64 {
353    fn histogram(meter: &Meter, declaration: &Declaration) -> otel::Histogram<Self> {
354        let mut builder = describe!(
355            meter.f64_histogram(declaration.exported_name()),
356            declaration
357        );
358        if let Some(buckets) = declaration.buckets {
359            builder = builder.with_boundaries(buckets.to_vec());
360        }
361        builder.build()
362    }
363}
364
365/// The labels of a metric group: a struct whose fields are the labels.
366/// Derive it:
367///
368/// ```ignore
369/// #[derive(Labels)]
370/// struct Outcome {
371///     method: &'static str,
372///     status: u16,
373/// }
374/// ```
375pub trait Labels {
376    /// Each label as an attribute, keyed by its name.
377    fn attributes(&self) -> Vec<KeyValue>;
378}
379
380/// A type a label's value can be: strings, integers, `bool` and `char` are.
381/// Implement it for an enum of your own to use it as a label:
382///
383/// ```ignore
384/// enum Plan { Free, Paid }
385///
386/// impl LabelValue for Plan {
387///     fn label_value(&self) -> Value {
388///         match self {
389///             Plan::Free => "free",
390///             Plan::Paid => "paid",
391///         }
392///         .into()
393///     }
394/// }
395/// ```
396pub trait LabelValue {
397    /// A string, an integer or a `bool`.
398    fn label_value(&self) -> Value;
399}
400
401impl LabelValue for str {
402    fn label_value(&self) -> Value {
403        self.to_string().into()
404    }
405}
406
407impl LabelValue for String {
408    fn label_value(&self) -> Value {
409        self.clone().into()
410    }
411}
412
413impl LabelValue for std::borrow::Cow<'_, str> {
414    fn label_value(&self) -> Value {
415        self.to_string().into()
416    }
417}
418
419impl LabelValue for char {
420    fn label_value(&self) -> Value {
421        self.to_string().into()
422    }
423}
424
425impl LabelValue for bool {
426    fn label_value(&self) -> Value {
427        Value::Bool(*self)
428    }
429}
430
431macro_rules! integer_label_values {
432    ($($ty:ty),*) => {$(
433        impl LabelValue for $ty {
434            /// An `i64`: one above `i64::MAX` is `i64::MAX`.
435            fn label_value(&self) -> Value {
436                Value::I64(i64::try_from(*self).unwrap_or(i64::MAX))
437            }
438        }
439    )*};
440}
441integer_label_values!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);
442
443impl<T: LabelValue + ?Sized> LabelValue for &T {
444    fn label_value(&self) -> Value {
445        (**self).label_value()
446    }
447}
448
449/// The options every metric is declared with.
450macro_rules! options {
451    ($what:literal) => {
452        #[doc = concat!("What the ", $what, " measures in, as exported: `\"s\"`, `\"By\"`, `\"{request}\"`.")]
453        pub const fn unit(mut self, unit: &'static str) -> Self {
454            self.declaration.unit = Some(unit);
455            self
456        }
457
458        #[doc = concat!("What the ", $what, " measures, for one without a doc comment.")]
459        pub const fn description(mut self, description: &'static str) -> Self {
460            self.declaration.description = Some(description);
461            self
462        }
463    };
464}
465
466/// The options a histogram is declared with, which a group's are too.
467macro_rules! histogram_options {
468    () => {
469        /// The upper bounds of the buckets, increasing: what is recorded is
470        /// counted in the first it is no greater than, or one past the last.
471        /// Without them, the OpenTelemetry SDK's defaults.
472        pub const fn buckets(mut self, bounds: &'static [f64]) -> Self {
473            self.declaration.buckets = Some(bounds);
474            self
475        }
476    };
477}
478
479/// A metric recorded to, its group, and their options.
480macro_rules! recorded {
481    (
482        $(#[$doc:meta])* $name:ident,
483        $(#[$group_doc:meta])* $group:ident,
484        own = $own:literal,
485        $what:literal,
486        $value:ident = $default:ty,
487        $instrument:ident :: $make:ident,
488        { $($options:tt)* }
489        { $($record:tt)* }
490    ) => {
491        $(#[$doc])*
492        pub struct $name<N: $value = $default> {
493            declaration: Declaration,
494            attributes: Vec<KeyValue>,
495            instrument: OnceLock<otel::$instrument<N>>,
496        }
497
498        impl<N: $value> $name<N> {
499            #[doc = concat!("Declares the ", $what, " `name`: a letter, then letters, digits, `_`, `.`, `-` and `/`. It must be a string literal: Encore reads it from the source.")]
500            pub const fn new(name: &'static str) -> Self {
501                Self {
502                    declaration: Declaration::new(name, $own),
503                    attributes: Vec::new(),
504                    instrument: OnceLock::new(),
505                }
506            }
507
508            options!($what);
509            $($options)*
510
511            #[doc = concat!("The ", $what, " itself, to hand to other code: a function that takes a `&", stringify!($name), "` records to whichever it is given.")]
512            ///
513            /// A metric is otherwise used where it is declared, by name, which
514            /// is how Encore sees which service records to it. Passing one on
515            /// says so explicitly, and counts as recording to it.
516            pub fn reference(&self) -> &Self {
517                self
518            }
519
520            $($record)*
521
522            fn instrument(&self) -> &otel::$instrument<N> {
523                self.instrument
524                    .get_or_init(|| N::$make(&meter(), &self.declaration))
525            }
526        }
527
528        $(#[$group_doc])*
529        pub struct $group<L: Labels, N: $value = $default> {
530            declaration: Declaration,
531            instrument: OnceLock<otel::$instrument<N>>,
532            _labels: PhantomData<fn(&L)>,
533        }
534
535        impl<L: Labels, N: $value> $group<L, N> {
536            #[doc = concat!("Declares the ", $what, " group `name`: a letter, then letters, digits, `_`, `.`, `-` and `/`. It must be a string literal: Encore reads it from the source.")]
537            pub const fn new(name: &'static str) -> Self {
538                Self {
539                    declaration: Declaration::new(name, $own),
540                    instrument: OnceLock::new(),
541                    _labels: PhantomData,
542                }
543            }
544
545            options!($what);
546            $($options)*
547
548            #[doc = concat!("The ", $what, " for `labels`. Worth keeping where it is used often: making it takes the labels' attributes.")]
549            pub fn with(&self, labels: &L) -> $name<N> {
550                let instrument = self
551                    .instrument
552                    .get_or_init(|| N::$make(&meter(), &self.declaration));
553                $name {
554                    declaration: self.declaration,
555                    attributes: labels.attributes(),
556                    instrument: OnceLock::from(instrument.clone()),
557                }
558            }
559
560            #[doc = concat!("The group itself, to hand to other code: a function that takes a `&", stringify!($group), "<L>` records to whichever it is given.")]
561            ///
562            /// A metric is otherwise used where it is declared, by name, which
563            /// is how Encore sees which service records to it. Passing one on
564            /// says so explicitly, and counts as recording to it.
565            pub fn reference(&self) -> &Self {
566                self
567            }
568        }
569    };
570}
571
572/// `named`, which a service's metric type and its group have: the bound
573/// metric's scope is its declaration's.
574macro_rules! named {
575    (false, $($_:tt)*) => {};
576    (true, $name:ident, $group:ident, $value:ident, $what:literal) => {
577        impl<N: $value> $name<N> {
578            #[doc = concat!("Binds the shared or global ", $what, " `name` declared elsewhere — by another service, possibly in another language — rather than declaring one. It is the declaration's kind and scope, and takes its unit, description and buckets: it has no options of its own. It is exported as `name`, never prefixed with a service's name. The name must be a string literal: Encore reads it from the source.")]
579            pub const fn named(name: &'static str) -> Self {
580                Self {
581                    declaration: Declaration::new(name, false),
582                    attributes: Vec::new(),
583                    instrument: OnceLock::new(),
584                }
585            }
586        }
587
588        impl<L: Labels, N: $value> $group<L, N> {
589            #[doc = concat!("Binds the shared or global ", $what, " group `name` declared elsewhere — by another service, possibly in another language — rather than declaring one. Its labels and scope are the declaration's, and it takes its unit, description and buckets: it has no options of its own. It is exported as `name`, never prefixed with a service's name. The name must be a string literal: Encore reads it from the source.")]
590            pub const fn named(name: &'static str) -> Self {
591                Self {
592                    declaration: Declaration::new(name, false),
593                    instrument: OnceLock::new(),
594                    _labels: PhantomData,
595                }
596            }
597        }
598    };
599}
600
601macro_rules! counter_types {
602    ($own:tt, $(#[$doc:meta])* $name:ident, $(#[$group_doc:meta])* $group:ident) => {
603        recorded!(
604            $(#[$doc])* $name,
605            $(#[$group_doc])* $group,
606            own = $own,
607            "counter",
608            CounterValue = u64,
609            Counter::counter,
610            {}
611            {
612                /// Adds one.
613                pub fn increment(&self) {
614                    self.add(N::ONE);
615                }
616
617                /// Adds `amount`. A counter does not go down: an amount below
618                /// zero is ignored.
619                pub fn add(&self, amount: N) {
620                    self.instrument().add(amount, &self.attributes);
621                }
622            }
623        );
624        named!($own, $name, $group, CounterValue, "counter");
625    };
626}
627
628counter_types!(
629    true,
630    /// A number that only goes up: how many times something happened, or how
631    /// much of something there has been. See the [module documentation](self).
632    ///
633    /// Declared as a module-level `static` inside a service, which alone
634    /// records to it: see [scope](self#scope).
635    Counter,
636    /// A [`Counter`] for each combination of the labels `L`.
637    CounterGroup
638);
639
640counter_types!(
641    false,
642    /// A [`Counter`] shared between services: each that records to it is
643    /// recorded as using it. See [scope](self#scope).
644    SharedCounter,
645    /// A [`SharedCounter`] for each combination of the labels `L`.
646    SharedCounterGroup
647);
648
649counter_types!(
650    false,
651    /// A [`Counter`] for the whole app, which any code may record to. See
652    /// [scope](self#scope).
653    GlobalCounter,
654    /// A [`GlobalCounter`] for each combination of the labels `L`.
655    GlobalCounterGroup
656);
657
658macro_rules! up_down_counter_types {
659    ($own:tt, $(#[$doc:meta])* $name:ident, $(#[$group_doc:meta])* $group:ident) => {
660        recorded!(
661            $(#[$doc])* $name,
662            $(#[$group_doc])* $group,
663            own = $own,
664            "up-down counter",
665            UpDownCounterValue = i64,
666            UpDownCounter::up_down_counter,
667            {}
668            {
669                /// Adds one.
670                pub fn increment(&self) {
671                    self.add(N::ONE);
672                }
673
674                /// Takes one away.
675                pub fn decrement(&self) {
676                    self.add(-N::ONE);
677                }
678
679                /// Adds `amount`, which may be below zero.
680                pub fn add(&self, amount: N) {
681                    self.instrument().add(amount, &self.attributes);
682                }
683            }
684        );
685        named!($own, $name, $group, UpDownCounterValue, "up-down counter");
686    };
687}
688
689up_down_counter_types!(
690    true,
691    /// A number that goes up and down by what is added to it: how many
692    /// requests are in flight, how many jobs are queued. See the [module
693    /// documentation](self).
694    ///
695    /// Declared as a module-level `static` inside a service, which alone
696    /// records to it: see [scope](self#scope).
697    UpDownCounter,
698    /// An [`UpDownCounter`] for each combination of the labels `L`.
699    UpDownCounterGroup
700);
701
702up_down_counter_types!(
703    false,
704    /// An [`UpDownCounter`] shared between services: each that records to it
705    /// is recorded as using it. See [scope](self#scope).
706    SharedUpDownCounter,
707    /// A [`SharedUpDownCounter`] for each combination of the labels `L`.
708    SharedUpDownCounterGroup
709);
710
711up_down_counter_types!(
712    false,
713    /// An [`UpDownCounter`] for the whole app, which any code may record to.
714    /// See [scope](self#scope).
715    GlobalUpDownCounter,
716    /// A [`GlobalUpDownCounter`] for each combination of the labels `L`.
717    GlobalUpDownCounterGroup
718);
719
720macro_rules! gauge_types {
721    ($own:tt, $(#[$doc:meta])* $name:ident, $(#[$group_doc:meta])* $group:ident) => {
722        recorded!(
723            $(#[$doc])* $name,
724            $(#[$group_doc])* $group,
725            own = $own,
726            "gauge",
727            GaugeValue = f64,
728            Gauge::gauge,
729            {}
730            {
731                /// Sets the gauge to `value`.
732                pub fn set(&self, value: N) {
733                    self.instrument().record(value, &self.attributes);
734                }
735            }
736        );
737        named!($own, $name, $group, GaugeValue, "gauge");
738    };
739}
740
741gauge_types!(
742    true,
743    /// A number that is what it was last set to: what something is right now.
744    /// See the [module documentation](self).
745    ///
746    /// Declared as a module-level `static` inside a service, which alone
747    /// records to it: see [scope](self#scope).
748    Gauge,
749    /// A [`Gauge`] for each combination of the labels `L`.
750    GaugeGroup
751);
752
753gauge_types!(
754    false,
755    /// A [`Gauge`] shared between services: each that records to it is
756    /// recorded as using it. See [scope](self#scope).
757    SharedGauge,
758    /// A [`SharedGauge`] for each combination of the labels `L`.
759    SharedGaugeGroup
760);
761
762gauge_types!(
763    false,
764    /// A [`Gauge`] for the whole app, which any code may record to. See
765    /// [scope](self#scope).
766    GlobalGauge,
767    /// A [`GlobalGauge`] for each combination of the labels `L`.
768    GlobalGaugeGroup
769);
770
771macro_rules! histogram_types {
772    ($own:tt, $(#[$doc:meta])* $name:ident, $(#[$group_doc:meta])* $group:ident) => {
773        recorded!(
774            $(#[$doc])* $name,
775            $(#[$group_doc])* $group,
776            own = $own,
777            "histogram",
778            HistogramValue = f64,
779            Histogram::histogram,
780            { histogram_options!(); }
781            {
782                /// Records `value`.
783                pub fn record(&self, value: N) {
784                    self.instrument().record(value, &self.attributes);
785                }
786            }
787        );
788        named!($own, $name, $group, HistogramValue, "histogram");
789    };
790}
791
792histogram_types!(
793    true,
794    /// How what is recorded is distributed: how long requests take, how large
795    /// uploads are. See the [module documentation](self).
796    ///
797    /// Declared as a module-level `static` inside a service, which alone
798    /// records to it: see [scope](self#scope).
799    Histogram,
800    /// A [`Histogram`] for each combination of the labels `L`.
801    HistogramGroup
802);
803
804histogram_types!(
805    false,
806    /// A [`Histogram`] shared between services: each that records to it is
807    /// recorded as using it. See [scope](self#scope).
808    SharedHistogram,
809    /// A [`SharedHistogram`] for each combination of the labels `L`.
810    SharedHistogramGroup
811);
812
813histogram_types!(
814    false,
815    /// A [`Histogram`] for the whole app, which any code may record to. See
816    /// [scope](self#scope).
817    GlobalHistogram,
818    /// A [`GlobalHistogram`] for each combination of the labels `L`.
819    GlobalHistogramGroup
820);
821
822#[cfg(test)]
823mod tests;