encore/metrics.rs
1//! Application metrics: counters, up-down counters, gauges, and histograms.
2//!
3//! Declare metrics as module-level `static`s and record measurements wherever
4//! the relevant events occur. A metric's doc comment is used as 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//! /// Oven temperature.
16//! static OVEN: Gauge = Gauge::new("oven_temperature").unit("Cel");
17//!
18//! /// Time taken to place an order.
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 metric is backed by an instrument from the
28//! [OpenTelemetry Metrics API](crate::opentelemetry::metrics) under the
29//! `encore.runtime` meter and is created on first use. Service-scoped metrics are
30//! automatically prefixed with the service name when exported (for example,
31//! `orders_placed` in service `shop` is exported as `shop.orders_placed`).
32//!
33//! You can also create custom OpenTelemetry instruments (including observable
34//! instruments) using [`meter_provider`]; they are exported alongside Encore
35//! metrics. Encore does not install a global meter provider:
36//!
37//! ```ignore
38//! use encore::opentelemetry::metrics::MeterProvider as _;
39//! let meter = encore::metrics::meter_provider().meter("my-app");
40//! let requests = meter.u64_counter("requests").build();
41//! requests.add(1, &[]);
42//! ```
43//!
44//! | Metric | Purpose | Supported value types |
45//! |---|---|---|
46//! | [`Counter`] | Monotonically increasing total | `u64`, `f64` |
47//! | [`UpDownCounter`] | Total that can increase or decrease | `i64`, `f64` |
48//! | [`Gauge`] | Point-in-time measurement | `f64`, `i64`, `u64` |
49//! | [`Histogram`] | Distribution of recorded values | `f64` |
50//!
51//! The first type listed for each metric is the default. Units follow the
52//! [UCUM](https://ucum.org/ucum) convention (for example, `"s"`, `"By"`,
53//! `"{request}"`). When a metric has no doc comment, you can provide a
54//! description with `.description(...)`.
55//!
56//! # Scope
57//!
58//! A metric's declaration determines which services can record to it, just like
59//! [secrets](crate::secrets#scope):
60//!
61//! - `Counter::new("requests")` (and `Gauge::new(...)`, etc.) belongs to the
62//! declaring service, and only that service may record to it. Names are
63//! unique per service: two services may each declare a `requests` counter,
64//! exported as `<service>.requests`. Must be declared inside a service.
65//! - `Counter::new("signups").shared()` is shared across services under a
66//! single app-wide name. Every service that records to it is tracked as a
67//! user.
68//! - `Counter::new("requests").global()` is available app-wide to any code
69//! (including shared libraries outside any service) without per-service
70//! tracking.
71//!
72//! Metric groups support the same scopes (for example,
73//! `CounterGroup::new("...").shared()`). Scope and option methods can be
74//! chained in any order, and both the name and scope must be written directly
75//! in the declaration so Encore can parse them statically.
76//!
77//! ```ignore
78//! /// Users signed up across all services.
79//! static SIGNUPS: Counter = Counter::new("signups").shared().unit("{user}");
80//! ```
81//!
82//! Declare a shared or global metric once in the app (just like a
83//! [shared secret](crate::secrets#scope)). Other code can record to it either
84//! by importing the `static` or, from another crate or language, by binding it
85//! with `named`:
86//!
87//! ```ignore
88//! static SERVED: CounterGroup<Served> = CounterGroup::named("greetings.served");
89//! ```
90//!
91//! A bound metric inherits the declaration's kind, labels, scope, unit,
92//! description, and histogram buckets, and is exported under the exact name
93//! given (never prefixed with a service name). To pass a metric to helper
94//! functions, use [`reference()`](Counter::reference); calling `reference()`
95//! counts as recording to the metric for static analysis.
96//!
97//! # Labels
98//!
99//! A plain metric ([`Counter`], [`Gauge`], etc.) records a single series. A
100//! *group* ([`CounterGroup`], [`GaugeGroup`], etc.) records a separate series
101//! for each combination of label values, defined as fields on a struct
102//! deriving [`Labels`]:
103//!
104//! ```ignore
105//! use encore::metrics::{CounterGroup, Labels};
106//!
107//! #[derive(Labels)]
108//! struct Outcome {
109//! method: &'static str,
110//! status: u16,
111//! }
112//!
113//! /// Requests handled, by method and status.
114//! static REQUESTS: CounterGroup<Outcome> = CounterGroup::new("requests_handled");
115//!
116//! REQUESTS.with(&Outcome { method: "GET", status: 200 }).increment();
117//! ```
118//!
119//! Each distinct label combination creates its own time series. Keep label
120//! cardinality low (such as status codes or regions) and avoid unbounded values
121//! like user IDs. For arbitrary attributes, use the OpenTelemetry API directly.
122//!
123//! # Histograms
124//!
125//! A [`Histogram`] aggregates measurements into buckets to measure
126//! distributions such as median or p99 latency. Custom
127//! [`buckets`](Histogram::buckets) are part of the metric definition and are
128//! exported as declared.
129//!
130//! # Testing
131//!
132//! Under `encore test` (and whenever the runtime does not export metrics),
133//! recording methods are no-ops.
134
135use std::marker::PhantomData;
136use std::sync::{Arc, OnceLock};
137
138use crate::opentelemetry::metrics::{self as otel, Meter, MeterProvider as _};
139use crate::opentelemetry::{InstrumentationScope, KeyValue, Value};
140use encore_sdk_core::telemetry::MeterProvider as CoreMeterProvider;
141
142use sealed::Declaration;
143
144/// Derives [`Labels`] for a struct with named fields. Each field becomes a
145/// metric label with the field's name and a value implementing [`LabelValue`].
146pub use encore_macros::Labels;
147
148/// OpenTelemetry [`MeterProvider`](otel::MeterProvider) backed by the Encore
149/// runtime. Cheap to clone.
150#[derive(Debug, Clone)]
151pub struct MeterProvider(Option<CoreMeterProvider>);
152
153impl otel::MeterProvider for MeterProvider {
154 fn meter_with_scope(&self, scope: InstrumentationScope) -> Meter {
155 match &self.0 {
156 Some(provider) => provider.meter_with_scope(scope),
157 None => Meter::new(Arc::new(NoInstruments)),
158 }
159 }
160}
161
162/// Makes instruments recording nothing.
163struct NoInstruments;
164
165impl otel::InstrumentProvider for NoInstruments {}
166
167impl MeterProvider {
168 /// Over `provider`, the runtime's; for none, recording nothing.
169 fn of(provider: Option<&CoreMeterProvider>) -> Self {
170 MeterProvider(provider.cloned())
171 }
172
173 /// Whether measurements are aggregated.
174 #[cfg(test)]
175 fn aggregates(&self) -> bool {
176 self.0.is_some()
177 }
178}
179
180/// Returns Encore's OpenTelemetry [`MeterProvider`], or a no-op provider when
181/// the runtime does not export metrics.
182pub fn meter_provider() -> MeterProvider {
183 MeterProvider::of(provider())
184}
185
186/// The meter every metric is an instrument of: `encore.runtime`, of this SDK's
187/// version, from Encore's meter provider.
188fn meter() -> Meter {
189 meter_provider().meter_with_scope(
190 InstrumentationScope::builder(encore_sdk_core::telemetry::scope::RUNTIME)
191 .with_version(env!("CARGO_PKG_VERSION"))
192 .build(),
193 )
194}
195
196/// The runtime's meter provider; none when the runtime exports no metrics.
197#[cfg(not(test))]
198fn provider() -> Option<&'static CoreMeterProvider> {
199 crate::runtime::core().resources().meter_provider()
200}
201
202// This crate's own tests run without a runtime.
203#[cfg(test)]
204fn provider() -> Option<&'static CoreMeterProvider> {
205 Some(tests::provider())
206}
207
208/// The service this process hosts, if any.
209#[cfg(not(test))]
210fn hosted_service() -> Option<&'static str> {
211 crate::runtime::core()
212 .runtime_config()
213 .current_service
214 .as_deref()
215}
216
217// This crate's own tests host `svc`.
218#[cfg(test)]
219fn hosted_service() -> Option<&'static str> {
220 Some("svc")
221}
222
223/// What a metric's value types make its instruments with, and its
224/// declaration: neither nameable outside this module.
225mod sealed {
226 use std::borrow::Cow;
227
228 use super::{hosted_service, otel, Meter};
229
230 /// What a metric is declared with.
231 #[derive(Debug, Clone, Copy)]
232 pub struct Declaration {
233 pub(super) name: &'static str,
234 /// The declaring service's alone, exported as `<service>.<name>`.
235 pub(super) own: bool,
236 pub(super) unit: Option<&'static str>,
237 pub(super) description: Option<&'static str>,
238 pub(super) buckets: Option<&'static [f64]>,
239 }
240
241 impl Declaration {
242 pub(super) const fn new(name: &'static str, own: bool) -> Self {
243 Self {
244 name,
245 own,
246 unit: None,
247 description: None,
248 buckets: None,
249 }
250 }
251
252 /// The instrument name: a service's own metric's is
253 /// `<service>.<name>`, of the service this process hosts.
254 pub(super) fn exported_name(&self) -> Cow<'static, str> {
255 match hosted_service() {
256 Some(service) if self.own => format!("{service}.{}", self.name).into(),
257 _ => self.name.into(),
258 }
259 }
260 }
261
262 pub trait Counter: Sized {
263 const ONE: Self;
264 fn counter(meter: &Meter, declaration: &Declaration) -> otel::Counter<Self>;
265 }
266
267 pub trait UpDownCounter: Sized {
268 const ONE: Self;
269 fn up_down_counter(meter: &Meter, declaration: &Declaration) -> otel::UpDownCounter<Self>;
270 }
271
272 pub trait Gauge: Sized {
273 fn gauge(meter: &Meter, declaration: &Declaration) -> otel::Gauge<Self>;
274 }
275
276 pub trait Histogram: Sized {
277 fn histogram(meter: &Meter, declaration: &Declaration) -> otel::Histogram<Self>;
278 }
279}
280
281/// An instrument builder with a declaration's unit and description.
282macro_rules! describe {
283 ($builder:expr, $declaration:expr) => {{
284 let mut builder = $builder;
285 if let Some(unit) = $declaration.unit {
286 builder = builder.with_unit(unit);
287 }
288 if let Some(description) = $declaration.description {
289 builder = builder.with_description(description);
290 }
291 builder
292 }};
293}
294
295/// Numeric types supported by [`Counter`]: `u64` (default) and `f64`.
296pub trait CounterValue: sealed::Counter + Copy + Send + Sync + 'static {}
297
298/// Numeric types supported by [`UpDownCounter`]: `i64` (default) and `f64`.
299pub trait UpDownCounterValue:
300 sealed::UpDownCounter + Copy + std::ops::Neg<Output = Self> + Send + Sync + 'static
301{
302}
303
304/// Numeric types supported by [`Gauge`]: `f64` (default), `i64`, and `u64`.
305pub trait GaugeValue: sealed::Gauge + Copy + Send + Sync + 'static {}
306
307/// Numeric types supported by [`Histogram`]: `f64`.
308pub trait HistogramValue: sealed::Histogram + Copy + Send + Sync + 'static {}
309
310macro_rules! counter_value {
311 ($ty:ty, $one:expr, $counter:ident) => {
312 impl CounterValue for $ty {}
313
314 impl sealed::Counter for $ty {
315 const ONE: Self = $one;
316
317 fn counter(meter: &Meter, declaration: &Declaration) -> otel::Counter<Self> {
318 describe!(meter.$counter(declaration.exported_name()), declaration).build()
319 }
320 }
321 };
322}
323counter_value!(u64, 1, u64_counter);
324counter_value!(f64, 1.0, f64_counter);
325
326macro_rules! up_down_counter_value {
327 ($ty:ty, $one:expr, $counter:ident) => {
328 impl UpDownCounterValue for $ty {}
329
330 impl sealed::UpDownCounter for $ty {
331 const ONE: Self = $one;
332
333 fn up_down_counter(
334 meter: &Meter,
335 declaration: &Declaration,
336 ) -> otel::UpDownCounter<Self> {
337 describe!(meter.$counter(declaration.exported_name()), declaration).build()
338 }
339 }
340 };
341}
342up_down_counter_value!(i64, 1, i64_up_down_counter);
343up_down_counter_value!(f64, 1.0, f64_up_down_counter);
344
345macro_rules! gauge_value {
346 ($ty:ty, $gauge:ident) => {
347 impl GaugeValue for $ty {}
348
349 impl sealed::Gauge for $ty {
350 fn gauge(meter: &Meter, declaration: &Declaration) -> otel::Gauge<Self> {
351 describe!(meter.$gauge(declaration.exported_name()), declaration).build()
352 }
353 }
354 };
355}
356gauge_value!(f64, f64_gauge);
357gauge_value!(i64, i64_gauge);
358gauge_value!(u64, u64_gauge);
359
360impl HistogramValue for f64 {}
361
362impl sealed::Histogram for f64 {
363 fn histogram(meter: &Meter, declaration: &Declaration) -> otel::Histogram<Self> {
364 let mut builder = describe!(
365 meter.f64_histogram(declaration.exported_name()),
366 declaration
367 );
368 if let Some(buckets) = declaration.buckets {
369 builder = builder.with_boundaries(buckets.to_vec());
370 }
371 builder.build()
372 }
373}
374
375/// Label set for a metric group, typically derived on a struct with named
376/// fields:
377///
378/// ```ignore
379/// #[derive(Labels)]
380/// struct Outcome {
381/// method: &'static str,
382/// status: u16,
383/// }
384/// ```
385pub trait Labels {
386 /// Converts the label fields into OpenTelemetry key-value attributes.
387 fn attributes(&self) -> Vec<KeyValue>;
388}
389
390/// Value types that can be used as metric labels.
391///
392/// Implemented out of the box for strings, integers, `bool`, and `char`.
393/// Implement this trait for custom enums to use them as labels:
394///
395/// ```ignore
396/// enum Plan { Free, Paid }
397///
398/// impl LabelValue for Plan {
399/// fn label_value(&self) -> Value {
400/// match self {
401/// Plan::Free => "free",
402/// Plan::Paid => "paid",
403/// }
404/// .into()
405/// }
406/// }
407/// ```
408pub trait LabelValue {
409 /// Converts this value into an OpenTelemetry attribute [`Value`] (string,
410 /// integer, or `bool`).
411 fn label_value(&self) -> Value;
412}
413
414impl LabelValue for str {
415 fn label_value(&self) -> Value {
416 self.to_string().into()
417 }
418}
419
420impl LabelValue for String {
421 fn label_value(&self) -> Value {
422 self.clone().into()
423 }
424}
425
426impl LabelValue for std::borrow::Cow<'_, str> {
427 fn label_value(&self) -> Value {
428 self.to_string().into()
429 }
430}
431
432impl LabelValue for char {
433 fn label_value(&self) -> Value {
434 self.to_string().into()
435 }
436}
437
438impl LabelValue for bool {
439 fn label_value(&self) -> Value {
440 Value::Bool(*self)
441 }
442}
443
444macro_rules! integer_label_values {
445 ($($ty:ty),*) => {$(
446 impl LabelValue for $ty {
447 /// Converts to an `i64` attribute value, clamping values above `i64::MAX`.
448 fn label_value(&self) -> Value {
449 Value::I64(i64::try_from(*self).unwrap_or(i64::MAX))
450 }
451 }
452 )*};
453}
454integer_label_values!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);
455
456impl<T: LabelValue + ?Sized> LabelValue for &T {
457 fn label_value(&self) -> Value {
458 (**self).label_value()
459 }
460}
461
462/// The options every metric is declared with.
463macro_rules! options {
464 ($what:literal) => {
465 #[doc = concat!("Declares the ", $what, " with shared app-wide scope rather than service scope. Any service may record to it, and each service that does is tracked as a user. See [scope](self#scope).")]
466 pub const fn shared(mut self) -> Self {
467 self.declaration.own = false;
468 self
469 }
470
471 #[doc = concat!("Declares the ", $what, " with global app-wide scope so any code (including shared libraries outside any service) may record to it without per-service tracking. See [scope](self#scope).")]
472 pub const fn global(mut self) -> Self {
473 self.declaration.own = false;
474 self
475 }
476
477 #[doc = concat!("Sets the exported unit of the ", $what, " (using UCUM notation such as `\"s\"`, `\"By\"`, or `\"{request}\"`).")]
478 pub const fn unit(mut self, unit: &'static str) -> Self {
479 self.declaration.unit = Some(unit);
480 self
481 }
482
483 #[doc = concat!("Sets the description of the ", $what, " when no doc comment is present.")]
484 pub const fn description(mut self, description: &'static str) -> Self {
485 self.declaration.description = Some(description);
486 self
487 }
488
489 #[doc = concat!("Attaches a key/value tag to the ", $what, " (for example, `.tag(\"data\", \"pii\")`) for policy and governance tooling. Call once per tag with unique keys. Both `key` and `value` must be string literals so Encore can parse them statically. Keys must start with a letter, contain only lowercase letters, digits, `_`, and `-`, and must not start with `encore` (reserved for Encore's own tags). Values use the same character set or may be empty. Each key and value is at most 63 characters, and a ", $what, " may have at most 32 tags.")]
490 ///
491 /// Tags classify the metric declaration itself and are distinct from
492 /// recorded metric labels.
493 pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
494 self
495 }
496 };
497}
498
499/// The options a histogram is declared with, which a group's are too.
500macro_rules! histogram_options {
501 () => {
502 /// Sets explicit increasing upper bucket boundaries.
503 ///
504 /// Each recorded value is counted in the first bucket whose upper bound
505 /// is greater than or equal to the value (or in an overflow bucket if
506 /// larger than all bounds). If omitted, OpenTelemetry's default bucket
507 /// boundaries are used.
508 pub const fn buckets(mut self, bounds: &'static [f64]) -> Self {
509 self.declaration.buckets = Some(bounds);
510 self
511 }
512 };
513}
514
515/// A metric recorded to, its group, and their options.
516macro_rules! recorded {
517 (
518 $(#[$doc:meta])* $name:ident,
519 $(#[$group_doc:meta])* $group:ident,
520 $what:literal,
521 $value:ident = $default:ty,
522 $instrument:ident :: $make:ident,
523 { $($options:tt)* }
524 { $($record:tt)* }
525 ) => {
526 $(#[$doc])*
527 pub struct $name<N: $value = $default> {
528 declaration: Declaration,
529 attributes: Vec<KeyValue>,
530 instrument: OnceLock<otel::$instrument<N>>,
531 }
532
533 impl<N: $value> $name<N> {
534 #[doc = concat!("Declares a ", $what, " with the given `name`. Names must start with a letter and contain only letters, digits, `_`, `.`, `-`, and `/`. `name` must be a string literal so Encore can parse it statically.")]
535 pub const fn new(name: &'static str) -> Self {
536 Self {
537 declaration: Declaration::new(name, true),
538 attributes: Vec::new(),
539 instrument: OnceLock::new(),
540 }
541 }
542
543 options!($what);
544 $($options)*
545
546 #[doc = concat!("Returns a reference to this ", $what, " that can be passed to helper functions taking `&", stringify!($name), "`.")]
547 ///
548 /// Calling `reference()` explicitly signals to Encore's static
549 /// analyzer that the calling service records to this metric.
550 pub fn reference(&self) -> &Self {
551 self
552 }
553
554 $($record)*
555
556 fn instrument(&self) -> &otel::$instrument<N> {
557 self.instrument
558 .get_or_init(|| N::$make(&meter(), &self.declaration))
559 }
560 }
561
562 $(#[$group_doc])*
563 pub struct $group<L: Labels, N: $value = $default> {
564 declaration: Declaration,
565 instrument: OnceLock<otel::$instrument<N>>,
566 _labels: PhantomData<fn(&L)>,
567 }
568
569 impl<L: Labels, N: $value> $group<L, N> {
570 #[doc = concat!("Declares a ", $what, " group with the given `name`. Names must start with a letter and contain only letters, digits, `_`, `.`, `-`, and `/`. `name` must be a string literal so Encore can parse it statically.")]
571 pub const fn new(name: &'static str) -> Self {
572 Self {
573 declaration: Declaration::new(name, true),
574 instrument: OnceLock::new(),
575 _labels: PhantomData,
576 }
577 }
578
579 options!($what);
580 $($options)*
581
582 #[doc = concat!("Returns a ", $what, " bound to the given `labels`. Cache the returned handle on hot paths to avoid recomputing label attributes on every recording.")]
583 pub fn with(&self, labels: &L) -> $name<N> {
584 let instrument = self
585 .instrument
586 .get_or_init(|| N::$make(&meter(), &self.declaration));
587 $name {
588 declaration: self.declaration,
589 attributes: labels.attributes(),
590 instrument: OnceLock::from(instrument.clone()),
591 }
592 }
593
594 #[doc = concat!("Returns a reference to this ", $what, " group that can be passed to helper functions taking `&", stringify!($group), "<L>`.")]
595 ///
596 /// Calling `reference()` explicitly signals to Encore's static
597 /// analyzer that the calling service records to this metric group.
598 pub fn reference(&self) -> &Self {
599 self
600 }
601 }
602
603 named!($name, $group, $value, $what);
604 };
605}
606
607/// `named`, which every metric type and its group have: the bound metric's
608/// scope is its declaration's.
609macro_rules! named {
610 ($name:ident, $group:ident, $value:ident, $what:literal) => {
611 impl<N: $value> $name<N> {
612 #[doc = concat!("Binds a shared or global ", $what, " named `name` that was declared elsewhere (for example, in another service or language). It inherits the declaration's kind, scope, unit, description, and buckets, and is exported as `name` without a service prefix. `name` must be a string literal so Encore can parse it statically.")]
613 pub const fn named(name: &'static str) -> Self {
614 Self {
615 declaration: Declaration::new(name, false),
616 attributes: Vec::new(),
617 instrument: OnceLock::new(),
618 }
619 }
620 }
621
622 impl<L: Labels, N: $value> $group<L, N> {
623 #[doc = concat!("Binds a shared or global ", $what, " group named `name` that was declared elsewhere (for example, in another service or language). It inherits the declaration's labels, scope, unit, description, and buckets, and is exported as `name` without a service prefix. `name` must be a string literal so Encore can parse it statically.")]
624 pub const fn named(name: &'static str) -> Self {
625 Self {
626 declaration: Declaration::new(name, false),
627 instrument: OnceLock::new(),
628 _labels: PhantomData,
629 }
630 }
631 }
632 };
633}
634
635recorded!(
636 /// A monotonically increasing counter for tracking event counts or
637 /// cumulative totals. See the [module documentation](self).
638 ///
639 /// Declare as a module-level `static`. Service-scoped by default unless
640 /// marked [`shared`](Self::shared) or [`global`](Self::global); see
641 /// [scope](self#scope).
642 Counter,
643 /// A [`Counter`] partitioned by labels of type `L`.
644 CounterGroup,
645 "counter",
646 CounterValue = u64,
647 Counter::counter,
648 {}
649 {
650 /// Increments the counter by 1.
651 pub fn increment(&self) {
652 self.add(N::ONE);
653 }
654
655 /// Adds `amount` to the counter. Negative values are ignored because
656 /// counters are monotonically increasing.
657 pub fn add(&self, amount: N) {
658 self.instrument().add(amount, &self.attributes);
659 }
660 }
661);
662
663recorded!(
664 /// A counter that can increase or decrease, useful for tracking values
665 /// such as in-flight requests or queue depth. See the
666 /// [module documentation](self).
667 ///
668 /// Declare as a module-level `static`. Service-scoped by default unless
669 /// marked [`shared`](Self::shared) or [`global`](Self::global); see
670 /// [scope](self#scope).
671 UpDownCounter,
672 /// An [`UpDownCounter`] partitioned by labels of type `L`.
673 UpDownCounterGroup,
674 "up-down counter",
675 UpDownCounterValue = i64,
676 UpDownCounter::up_down_counter,
677 {}
678 {
679 /// Increments the counter by 1.
680 pub fn increment(&self) {
681 self.add(N::ONE);
682 }
683
684 /// Decrements the counter by 1.
685 pub fn decrement(&self) {
686 self.add(-N::ONE);
687 }
688
689 /// Adds `amount` to the counter (may be negative).
690 pub fn add(&self, amount: N) {
691 self.instrument().add(amount, &self.attributes);
692 }
693 }
694);
695
696recorded!(
697 /// A point-in-time gauge holding its most recently recorded value. See the
698 /// [module documentation](self).
699 ///
700 /// Declare as a module-level `static`. Service-scoped by default unless
701 /// marked [`shared`](Self::shared) or [`global`](Self::global); see
702 /// [scope](self#scope).
703 Gauge,
704 /// A [`Gauge`] partitioned by labels of type `L`.
705 GaugeGroup,
706 "gauge",
707 GaugeValue = f64,
708 Gauge::gauge,
709 {}
710 {
711 /// Sets the gauge to `value`.
712 pub fn set(&self, value: N) {
713 self.instrument().record(value, &self.attributes);
714 }
715 }
716);
717
718recorded!(
719 /// A histogram for tracking value distributions such as request latencies
720 /// or payload sizes. See the [module documentation](self).
721 ///
722 /// Declare as a module-level `static`. Service-scoped by default unless
723 /// marked [`shared`](Self::shared) or [`global`](Self::global); see
724 /// [scope](self#scope).
725 Histogram,
726 /// A [`Histogram`] partitioned by labels of type `L`.
727 HistogramGroup,
728 "histogram",
729 HistogramValue = f64,
730 Histogram::histogram,
731 { histogram_options!(); }
732 {
733 /// Records a single observation `value`.
734 pub fn record(&self, value: N) {
735 self.instrument().record(value, &self.attributes);
736 }
737 }
738);
739
740#[cfg(test)]
741mod tests;