use lazy_static::lazy_static; use prometheus::{IntCounterVec, Opts, Registry}; use rocket::{ fairing::{Fairing, Info, Kind}, Data, Request, Response, }; lazy_static! { pub static ref REGISTRY: Registry = Registry::new(); static ref REQUEST_COUNTER: IntCounterVec = IntCounterVec::new(Opts::new("requests", "Requests"), &["method", "route"]).unwrap(); static ref RESPONSE_COUNTER: IntCounterVec = IntCounterVec::new(Opts::new("responses", "Responses"), &["status", "route"]).unwrap(); } pub fn init_metrics() { REGISTRY.register(Box::new(REQUEST_COUNTER.clone())).unwrap(); } pub struct MetricProducer; #[rocket::async_trait] impl Fairing for MetricProducer { fn info(&self) -> Info { Info { name: "Metrics fairing", kind: Kind::Request } } async fn on_request(&self, req: &mut Request<'_>, _data: &mut Data<'_>) { if let Some(route) = req.route() { REQUEST_COUNTER .with_label_values(&[req.method().as_str(), &route.uri.to_string()]) .inc(); } } async fn on_response<'r>(&self, req: &'r Request<'_>, resp: &mut Response<'r>) { if let Some(route) = req.route() { RESPONSE_COUNTER .with_label_values(&[&resp.status().code.to_string(), &route.uri.to_string()]) .inc(); } } }