Fix concurrent request spans interfering

This commit is contained in:
Michael Pfaff 2021-01-20 22:56:09 -05:00
parent 53eac89cae
commit ea1ed6fd70
Signed by: michael
GPG Key ID: E53B118B12B5C7F9
1 changed files with 9 additions and 7 deletions

View File

@ -7,25 +7,27 @@ use nrid::Nrid;
use std::time::Instant;
use tide::Next;
use tide::Request;
use tracing::Instrument;
use tracing::Level;
/// Middleware for the [`req_access_token!`] macro.
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 {
Box::pin(async move {
let now = Instant::now();
let id = Nrid::now();
let uri = req.url();
let uri = req.url().clone();
// 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 _enter = span.enter();
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");
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;
Ok(res)
})
}