Skip to content

Commit

Permalink
add basic axum metrics handler
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffgrunewald committed Mar 5, 2024
1 parent f33d90a commit 5c28d3e
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ members = [
"crates/dscvr-canister-config",
"crates/dscvr-canister-exports",
"crates/dscvr-interface",
"crates/dscvr-telemetry-util",
"crates/dscvr-tracing-util",
"crates/ic-canister-io",
"crates/ic-canister-logger",
Expand Down
10 changes: 10 additions & 0 deletions crates/dscvr-telemetry-util/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "dscvr-telemetry-util"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.6"
http = "0"
metrics = "0"
metrics-exporter-prometheus = "0"
30 changes: 30 additions & 0 deletions crates/dscvr-telemetry-util/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use axum::{extract::MatchedPath, middleware::Next, response::Response};
use http::Request;
use std::time::Instant;

pub async fn track_metrics<B>(req: Request<B>, next: Next<B>) -> Response {
let start = Instant::now();
let path = req
.extensions()
.get::<MatchedPath>()
.map(|path| path.as_str().to_owned());
let method = req.method().clone();

let response = next.run(req).await;

if let Some(path) = path {
let latency = start.elapsed().as_secs_f64();
let status = response.status().as_u16().to_string();

let labels = [
("method", method.to_string()),
("path", path.as_str().to_owned()),
("status", status),
];

metrics::counter!("rpc-request-count", &labels).increment(1);
metrics::histogram!("rpc-request-duration", &labels).record(latency);
}

response
}

0 comments on commit 5c28d3e

Please sign in to comment.