init4_bin_base/utils/
metrics.rs1use crate::utils::from_env::{FromEnv, FromEnvErr, FromEnvVar};
2use metrics_exporter_prometheus::PrometheusBuilder;
3
4use super::from_env::EnvItemInfo;
5
6const METRICS_PORT: &str = "METRICS_PORT";
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
15#[non_exhaustive]
16#[serde(from = "Option<u16>")]
17pub struct MetricsConfig {
18 pub port: u16,
21}
22
23impl Default for MetricsConfig {
24 fn default() -> Self {
25 Self { port: 9000 }
26 }
27}
28
29impl From<Option<u16>> for MetricsConfig {
30 fn from(port: Option<u16>) -> Self {
31 Self {
32 port: port.unwrap_or(9000),
33 }
34 }
35}
36
37impl From<u16> for MetricsConfig {
38 fn from(port: u16) -> Self {
39 Self { port }
40 }
41}
42
43impl FromEnv for MetricsConfig {
44 type Error = std::num::ParseIntError;
45
46 fn inventory() -> Vec<&'static EnvItemInfo> {
47 vec![&EnvItemInfo {
48 var: METRICS_PORT,
49 description: "Port on which to serve metrics, u16, defaults to 9000",
50 optional: true,
51 }]
52 }
53
54 fn from_env() -> Result<Self, FromEnvErr<Self::Error>> {
55 match u16::from_env_var(METRICS_PORT).map(Self::from) {
56 Ok(cfg) => Ok(cfg),
57 Err(_) => Ok(Self::default()),
58 }
59 }
60}
61
62pub fn init_metrics() {
75 let cfg = MetricsConfig::from_env().unwrap();
76
77 PrometheusBuilder::new()
78 .with_http_listener(([0, 0, 0, 0], cfg.port))
79 .install()
80 .expect("failed to install prometheus exporter");
81}