tide-tracing/src/lib.rs

34 lines
1.1 KiB
Rust
Raw Normal View History

2021-01-18 22:39:08 -05:00
#[macro_use]
extern crate tracing;
use core::future::Future;
use core::pin::Pin;
use nrid::Nrid;
use std::time::Instant;
use tide::Next;
use tide::Request;
use tracing::Instrument;
2021-01-18 22:39:08 -05:00
use tracing::Level;
pub fn log_middleware<'a, State: 'static + Clone + Send + Sync>(
req: Request<State>,
next: Next<'a, State>,
) -> Pin<Box<dyn Future<Output = tide::Result> + Send + 'a>> {
Box::pin(async move {
2021-01-18 22:39:08 -05:00
let now = Instant::now();
let id = Nrid::now();
let uri = req.url().clone();
2021-01-18 22:39:08 -05:00
// doesn't take forwarding into account and includes useless socket port information
// let ip = req.peer_addr().unwrap_or("unknown").to_string();
let ip = req.remote().unwrap_or("unknown").to_string();
let span = span!(Level::ERROR, "Request", id = %id);
let res = async {
debug!(req.method = %req.method(), req.uri.path = uri.path(), req.uri.query = uri.query().unwrap_or(""), client_ip = %ip, received = ?now);
let res = next.run(req).await;
debug!(status = %res.status(), elapsed = ?now.elapsed(), "Response");
res
}.instrument(span).await;
2021-01-18 22:39:08 -05:00
Ok(res)
})
}