1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use crate::{
middleware::{Middleware, Next},
Request, Response,
};
use futures::future::BoxFuture;
#[derive(Debug, Clone, Default)]
pub struct RequestLogger;
impl RequestLogger {
pub fn new() -> Self {
Self::default()
}
async fn log_basic<'a, State: Send + Sync + 'static>(
&'a self,
ctx: Request<State>,
next: Next<'a, State>,
) -> Response {
let path = ctx.uri().path().to_owned();
let method = ctx.method().as_str().to_owned();
log::trace!("IN => {} {}", method, path);
let start = std::time::Instant::now();
let res = next.run(ctx).await;
let status = res.status();
log::info!(
"{} {} {} {}ms",
method,
path,
status.as_str(),
start.elapsed().as_millis()
);
res
}
}
impl<State: Send + Sync + 'static> Middleware<State> for RequestLogger {
fn handle<'a>(&'a self, ctx: Request<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
Box::pin(async move { self.log_basic(ctx, next).await })
}
}