From 54c33a7aff8063f60d6648aa50863081287cba96 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Tue, 8 May 2018 16:30:34 -0700 Subject: [PATCH] Allow to exclude certain endpoints from logging #211 --- CHANGES.md | 2 ++ src/middleware/logger.rs | 35 +++++++++++++++++++++++------------ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 7be1c98e..cc8151dd 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -8,6 +8,8 @@ * Send `ErrorNotFound` instead of `ErrorBadRequest` when path extractor fails #214 +* Allow to exclude certain endpoints from logging #211 + ## 0.6.0 (2018-05-08) * Add route scopes #202 diff --git a/src/middleware/logger.rs b/src/middleware/logger.rs index adfc3d2b..086c232c 100644 --- a/src/middleware/logger.rs +++ b/src/middleware/logger.rs @@ -1,7 +1,7 @@ //! Request logging middleware +use std::collections::HashSet; use std::env; -use std::fmt; -use std::fmt::{Display, Formatter}; +use std::fmt::{self, Display, Formatter}; use libc; use regex::Regex; @@ -74,6 +74,7 @@ use middleware::{Finished, Middleware, Started}; /// pub struct Logger { format: Format, + exclude: HashSet, } impl Logger { @@ -81,8 +82,15 @@ impl Logger { pub fn new(format: &str) -> Logger { Logger { format: Format::new(format), + exclude: HashSet::new(), } } + + /// Ignore and do not log access info for specified path. + pub fn exclude>(mut self, path: T) -> Self { + self.exclude.insert(path.into()); + self + } } impl Default for Logger { @@ -94,6 +102,7 @@ impl Default for Logger { fn default() -> Logger { Logger { format: Format::default(), + exclude: HashSet::new(), } } } @@ -102,21 +111,23 @@ struct StartTime(time::Tm); impl Logger { fn log(&self, req: &mut HttpRequest, resp: &HttpResponse) { - let entry_time = req.extensions().get::().unwrap().0; - - let render = |fmt: &mut Formatter| { - for unit in &self.format.0 { - unit.render(fmt, req, resp, entry_time)?; - } - Ok(()) - }; - info!("{}", FormatDisplay(&render)); + if let Some(entry_time) = req.extensions().get::() { + let render = |fmt: &mut Formatter| { + for unit in &self.format.0 { + unit.render(fmt, req, resp, entry_time.0)?; + } + Ok(()) + }; + info!("{}", FormatDisplay(&render)); + } } } impl Middleware for Logger { fn start(&self, req: &mut HttpRequest) -> Result { - req.extensions_mut().insert(StartTime(time::now())); + if !self.exclude.contains(req.path()) { + req.extensions_mut().insert(StartTime(time::now())); + } Ok(Started::Done) }