use anyhow::{Result, anyhow};
use metrics::Recorder;
use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle, PrometheusRecorder};
#[derive(Default)]
pub struct MetricsRegistry {
prometheus_handle: Option<PrometheusHandle>,
}
impl MetricsRegistry {
pub fn install_default_prometheus_if_unset() -> Result<Self> {
let recorder = PrometheusBuilder::new().build_recorder();
let handle = recorder.handle();
match metrics::set_global_recorder(recorder) {
Ok(()) => Ok(Self {
prometheus_handle: Some(handle),
}),
Err(_) => Ok(Self {
prometheus_handle: None,
}),
}
}
pub fn install_external_recorder<R>(recorder: R) -> Result<Self>
where
R: Recorder + Send + Sync + 'static,
{
metrics::set_global_recorder(recorder)
.map_err(|_| anyhow!("failed to set external metrics recorder"))?;
Ok(Self {
prometheus_handle: None,
})
}
pub fn install_external_prometheus_recorder(recorder: PrometheusRecorder) -> Result<Self> {
let handle = recorder.handle();
metrics::set_global_recorder(recorder)
.map_err(|_| anyhow!("failed to set external Prometheus recorder"))?;
Ok(Self {
prometheus_handle: Some(handle),
})
}
pub fn prometheus_handle(&self) -> Option<PrometheusHandle> {
self.prometheus_handle.clone()
}
}