How to Add Metrics to a Rust Application (prometheus, metrics crate)
Add the metrics crate to your Cargo.toml, initialize the recorder in main, and export metrics using the metrics::counter! macro.
[dependencies]
metrics = "0.24"
metrics-util = "0.19"
metrics-exporter-prometheus = "0.16"
use metrics::{counter, set_global_recorder};
use metrics_util::recorder::AggregationRecorder;
use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
fn main() {
let recorder = AggregationRecorder::new();
let handle = PrometheusBuilder::new()
.install_recorder(&recorder)
.unwrap();
counter!("http_requests_total", "method" => "GET").increment(1);
// Serve metrics at /metrics via handle.render() in your HTTP handler
println!("Metrics available via handle.render()");
}