2021-01-18 22:39:08 -05:00
|
|
|
#[macro_use]
|
|
|
|
extern crate tracing;
|
|
|
|
|
2021-01-21 11:49:00 -05:00
|
|
|
use chrono::Utc;
|
2021-01-18 22:39:08 -05:00
|
|
|
use nrid::Nrid;
|
2021-01-21 11:49:00 -05:00
|
|
|
use tide::Middleware;
|
2021-01-18 22:39:08 -05:00
|
|
|
use tide::Next;
|
|
|
|
use tide::Request;
|
2021-01-20 22:56:09 -05:00
|
|
|
use tracing::Instrument;
|
2021-01-18 22:39:08 -05:00
|
|
|
use tracing::Level;
|
|
|
|
|
2021-01-21 11:49:00 -05:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct LogMiddleware {
|
2021-01-21 11:52:22 -05:00
|
|
|
pub include_ip: bool,
|
|
|
|
pub include_query: bool,
|
2021-01-21 11:49:00 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for LogMiddleware {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
|
|
|
include_ip: false,
|
|
|
|
include_query: false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl LogMiddleware {
|
|
|
|
async fn log<'a, State: Clone + Send + Sync + 'static>(
|
|
|
|
&'a self,
|
|
|
|
req: Request<State>,
|
|
|
|
next: Next<'a, State>,
|
|
|
|
) -> tide::Result {
|
|
|
|
let start = Utc::now();
|
2021-01-18 22:39:08 -05:00
|
|
|
let id = Nrid::now();
|
2021-01-20 22:56:09 -05:00
|
|
|
let uri = req.url().clone();
|
2021-01-18 22:39:08 -05:00
|
|
|
let ip = req.remote().unwrap_or("unknown").to_string();
|
|
|
|
let span = span!(Level::ERROR, "Request", id = %id);
|
2021-01-20 22:56:09 -05:00
|
|
|
let res = async {
|
2021-01-21 11:49:00 -05:00
|
|
|
debug!(path = uri.path());
|
|
|
|
|
|
|
|
debug!(method = %req.method());
|
|
|
|
|
|
|
|
if self.include_query {
|
|
|
|
debug!(query = uri.query().unwrap_or(""));
|
|
|
|
}
|
|
|
|
|
|
|
|
if self.include_ip {
|
|
|
|
debug!(client_ip = %ip);
|
|
|
|
}
|
|
|
|
|
|
|
|
debug!(received = %start);
|
|
|
|
// debug!(method = %req.method(), query = uri.query().unwrap_or(""), client_ip = %ip, received = %start, "Request recieved");
|
2021-01-20 22:56:09 -05:00
|
|
|
let res = next.run(req).await;
|
2021-01-21 11:49:00 -05:00
|
|
|
let end = Utc::now();
|
|
|
|
let span = span!(Level::ERROR, "Response");
|
|
|
|
async {
|
|
|
|
debug!(status = %res.status());
|
|
|
|
debug!(duration = %end.signed_duration_since(start));
|
|
|
|
}.instrument(span).await;
|
2021-01-20 22:56:09 -05:00
|
|
|
res
|
|
|
|
}.instrument(span).await;
|
2021-01-18 22:39:08 -05:00
|
|
|
Ok(res)
|
2021-01-21 11:49:00 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait::async_trait]
|
|
|
|
impl<State: Clone + Send + Sync + 'static> Middleware<State> for LogMiddleware {
|
|
|
|
async fn handle(&self, req: Request<State>, next: Next<'_, State>) -> tide::Result {
|
|
|
|
self.log(req, next).await
|
|
|
|
}
|
2021-01-18 22:39:08 -05:00
|
|
|
}
|