init4_bin_base/utils/
metrics.rs1use crate::utils::from_env::{FromEnv, FromEnvErr, FromEnvVar};
2use metrics_exporter_prometheus::PrometheusBuilder;
3
4const METRICS_PORT: &str = "METRICS_PORT";
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct MetricsConfig {
15 pub port: u16,
18}
19
20impl Default for MetricsConfig {
21 fn default() -> Self {
22 Self { port: 9000 }
23 }
24}
25
26impl From<Option<u16>> for MetricsConfig {
27 fn from(port: Option<u16>) -> Self {
28 Self {
29 port: port.unwrap_or(9000),
30 }
31 }
32}
33
34impl From<u16> for MetricsConfig {
35 fn from(port: u16) -> Self {
36 Self { port }
37 }
38}
39
40impl FromEnv for MetricsConfig {
41 type Error = std::num::ParseIntError;
42
43 fn from_env() -> Result<Self, FromEnvErr<Self::Error>> {
44 match u16::from_env_var(METRICS_PORT).map(Self::from) {
45 Ok(cfg) => Ok(cfg),
46 Err(_) => Ok(Self::default()),
47 }
48 }
49}
50
51pub fn init_metrics() {
64 let cfg = MetricsConfig::from_env().unwrap();
65
66 PrometheusBuilder::new()
67 .with_http_listener(([0, 0, 0, 0], cfg.port))
68 .install()
69 .expect("failed to install prometheus exporter");
70}