|
| 1 | +use std::{ |
| 2 | + convert::Infallible, |
| 3 | + pin::Pin, |
| 4 | + task::{Context, Poll}, |
| 5 | +}; |
| 6 | + |
| 7 | +use axum::{extract::Request, response::Response}; |
| 8 | +use futures_util::Future; |
| 9 | +use tower::{Layer, Service}; |
| 10 | +use tracing::Level; |
| 11 | + |
| 12 | +pub const METRICS_TARGET: &str = "metrics"; |
| 13 | + |
| 14 | +#[derive(Clone)] |
| 15 | +pub struct RequestMetricsLayer {} |
| 16 | + |
| 17 | +impl RequestMetricsLayer { |
| 18 | + pub fn new() -> Self { |
| 19 | + Self {} |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl<S> Layer<S> for RequestMetricsLayer { |
| 24 | + type Service = RequestMetricsService<S>; |
| 25 | + |
| 26 | + fn layer(&self, inner: S) -> Self::Service { |
| 27 | + RequestMetricsService { inner } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +#[derive(Clone)] |
| 32 | +pub struct RequestMetricsService<S> { |
| 33 | + inner: S, |
| 34 | +} |
| 35 | + |
| 36 | +impl<S> Service<Request> for RequestMetricsService<S> |
| 37 | +where |
| 38 | + S: Service<Request, Response = Response, Error = Infallible> + Clone + Send + 'static, |
| 39 | + S::Future: Send, |
| 40 | +{ |
| 41 | + type Response = Response; |
| 42 | + type Error = Infallible; |
| 43 | + type Future = |
| 44 | + Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>; |
| 45 | + |
| 46 | + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { |
| 47 | + self.inner.poll_ready(cx) |
| 48 | + } |
| 49 | + |
| 50 | + fn call(&mut self, req: Request) -> Self::Future { |
| 51 | + let path = req.uri().path().to_owned(); |
| 52 | + |
| 53 | + let mut this = self.clone(); |
| 54 | + Box::pin(async move { |
| 55 | + let response = this.inner.call(req).await.unwrap(); |
| 56 | + let status = response.status().as_u16(); |
| 57 | + |
| 58 | + tracing::event!(target: METRICS_TARGET, Level::INFO, monotonic_counter.request = 1, path, status); |
| 59 | + |
| 60 | + Ok(response) |
| 61 | + }) |
| 62 | + } |
| 63 | +} |
0 commit comments