Skip to content

Move request logging near the top of the middleware stack #2383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ pub fn build_middleware(app: Arc<App>, endpoints: R404) -> MiddlewareBuilder {

if env != Env::Test {
m.add(ensure_well_formed_500::EnsureWellFormed500);
m.add(log_request::LogRequests::default());
}

if env == Env::Development {
Expand Down Expand Up @@ -94,9 +95,5 @@ pub fn build_middleware(app: Arc<App>, endpoints: R404) -> MiddlewareBuilder {

m.around(require_user_agent::RequireUserAgent::default());

if env != Env::Test {
m.around(log_request::LogRequests::default());
}

m
}
23 changes: 11 additions & 12 deletions src/middleware/log_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,21 @@ use std::time::Instant;

const SLOW_REQUEST_THRESHOLD_MS: u64 = 1000;

#[allow(missing_debug_implementations)] // We can't
#[derive(Default)]
pub struct LogRequests {
handler: Option<Box<dyn Handler>>,
}
pub(super) struct LogRequests();

struct RequestStart(Instant);

impl AroundMiddleware for LogRequests {
fn with_handler(&mut self, handler: Box<dyn Handler>) {
self.handler = Some(handler);
impl Middleware for LogRequests {
fn before(&self, req: &mut dyn Request) -> Result<()> {
req.mut_extensions().insert(RequestStart(Instant::now()));
Ok(())
}
}

impl Handler for LogRequests {
fn call(&self, req: &mut dyn Request) -> Result<Response> {
let request_start = Instant::now();
let res = self.handler.as_ref().unwrap().call(req);
fn after(&self, req: &mut dyn Request, res: Result<Response>) -> Result<Response> {
// Unwrap shouldn't panic as no other code has access to the private struct to remove it
let request_start = req.extensions().find::<RequestStart>().unwrap().0;

let response_time = request_start.elapsed();
let response_time =
response_time.as_secs() * 1000 + u64::from(response_time.subsec_nanos()) / 1_000_000;
Expand Down