monocle_agent/metrics.rs
1//! Ergonomic helpers to record custom application metrics without naming
2//! `opentelemetry` directly.
3//!
4//! Each helper builds an instrument against the global meter installed by
5//! [`crate::init`]. When telemetry is disabled (no `MONOCLE_API_KEY`) the global
6//! meter is a no-op, so recording is a cheap no-op too — you never branch on
7//! whether export is on.
8//!
9//! Build an instrument **once** and reuse it (instruments are cheap to record,
10//! not to create):
11//!
12//! ```
13//! use std::sync::LazyLock;
14//! use monocle_agent::opentelemetry::metrics::Counter;
15//!
16//! static JOBS: LazyLock<Counter<u64>> =
17//! LazyLock::new(|| monocle_agent::counter("jobs.processed", "Jobs processed"));
18//!
19//! JOBS.add(1, &[]);
20//! ```
21//!
22//! Need a custom instrumentation scope or an instrument type not covered here?
23//! Drop down to [`crate::opentelemetry`]`::global::meter(...)`.
24
25use opentelemetry::metrics::{Counter, Gauge, Histogram};
26
27/// Instrumentation scope used for helper-created instruments.
28const SCOPE: &str = "monocle-agent";
29
30/// Create a monotonic `u64` counter (e.g. requests, jobs, errors).
31pub fn counter(
32 name: impl Into<std::borrow::Cow<'static, str>>,
33 description: impl Into<std::borrow::Cow<'static, str>>,
34) -> Counter<u64> {
35 opentelemetry::global::meter(SCOPE)
36 .u64_counter(name)
37 .with_description(description)
38 .build()
39}
40
41/// Create an `f64` histogram (e.g. durations, sizes). `unit` follows UCUM
42/// (`"s"` for seconds, `"By"` for bytes, `""` for dimensionless).
43pub fn histogram(
44 name: impl Into<std::borrow::Cow<'static, str>>,
45 unit: impl Into<std::borrow::Cow<'static, str>>,
46 description: impl Into<std::borrow::Cow<'static, str>>,
47) -> Histogram<f64> {
48 opentelemetry::global::meter(SCOPE)
49 .f64_histogram(name)
50 .with_unit(unit)
51 .with_description(description)
52 .build()
53}
54
55/// Create an `f64` gauge for a last-value measurement (e.g. queue depth,
56/// temperature, in-flight requests).
57pub fn gauge(
58 name: impl Into<std::borrow::Cow<'static, str>>,
59 description: impl Into<std::borrow::Cow<'static, str>>,
60) -> Gauge<f64> {
61 opentelemetry::global::meter(SCOPE)
62 .f64_gauge(name)
63 .with_description(description)
64 .build()
65}