metrics.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #[cfg(feature = "prometheus")]
  2. use std::time::Instant;
  3. #[cfg(feature = "prometheus")]
  4. use axum::body::Body;
  5. #[cfg(feature = "prometheus")]
  6. use axum::extract::MatchedPath;
  7. #[cfg(feature = "prometheus")]
  8. use axum::http::Request;
  9. #[cfg(feature = "prometheus")]
  10. use axum::middleware::Next;
  11. #[cfg(feature = "prometheus")]
  12. use axum::response::Response;
  13. #[cfg(feature = "prometheus")]
  14. use cdk_prometheus::global;
  15. /// Global metrics middleware that uses the singleton instance.
  16. /// This version doesn't require access to MintState and can be used in any Axum application.
  17. #[cfg(feature = "prometheus")]
  18. pub async fn global_metrics_middleware(
  19. matched_path: Option<MatchedPath>,
  20. req: Request<Body>,
  21. next: Next,
  22. ) -> Response {
  23. let start_time = Instant::now();
  24. let response = next.run(req).await;
  25. let endpoint_path = matched_path
  26. .map(|mp| mp.as_str().to_string())
  27. .unwrap_or_default();
  28. let status_code = response.status().as_u16().to_string();
  29. let request_duration = start_time.elapsed().as_secs_f64();
  30. // Always use global metrics
  31. global::record_http_request(&endpoint_path, &status_code);
  32. global::record_http_request_duration(request_duration, &endpoint_path);
  33. response
  34. }