iroh_metrics/metrics.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
//! Metrics collection
//!
//! Enables and manages a global registry of metrics.
//! Divided up into modules, each module has its own metrics.
//! Starting the metrics service will expose the metrics on a OpenMetrics http endpoint.
//!
//! To enable metrics collection, call `init_metrics()` before starting the service.
//!
//! - To increment a **counter**, use the [`crate::inc`] macro with a value.
//! - To increment a **counter** by 1, use the [`crate::inc_by`] macro.
//!
//! To expose the metrics, start the metrics service with `start_metrics_server()`.
//!
//! # Example:
//! ```rust
//! use iroh_metrics::{inc, inc_by};
//! use iroh_metrics::core::{Core, Metric, Counter};
//! use struct_iterable::Iterable;
//!
//! #[derive(Debug, Clone, Iterable)]
//! pub struct Metrics {
//! pub things_added: Counter,
//! }
//!
//! impl Default for Metrics {
//! fn default() -> Self {
//! Self {
//! things_added: Counter::new("things_added tracks the number of things we have added"),
//! }
//! }
//! }
//!
//! impl Metric for Metrics {
//! fn name() -> &'static str {
//! "my_metrics"
//! }
//! }
//!
//! Core::init(|reg, metrics| {
//! metrics.insert(Metrics::new(reg));
//! });
//!
//! inc_by!(Metrics, things_added, 2);
//! inc!(Metrics, things_added);
//! ```
// TODO: move cfg to lib.rs
#[cfg(feature = "metrics")]
use std::net::SocketAddr;
/// Start a server to serve the OpenMetrics endpoint.
#[cfg(feature = "metrics")]
pub async fn start_metrics_server(addr: SocketAddr) -> anyhow::Result<()> {
crate::service::run(addr).await
}
/// Start a metrics dumper service.
#[cfg(feature = "metrics")]
pub async fn start_metrics_dumper(
path: std::path::PathBuf,
interval: std::time::Duration,
) -> anyhow::Result<()> {
crate::service::dumper(&path, interval).await
}
/// Start a metrics exporter service.
#[cfg(feature = "metrics")]
pub async fn start_metrics_exporter(cfg: crate::PushMetricsConfig) {
crate::service::exporter(
cfg.endpoint,
cfg.service_name,
cfg.instance_name,
cfg.username,
cfg.password,
std::time::Duration::from_secs(cfg.interval),
)
.await;
}