1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 00:21:08 +01:00

Allow to exclude certain endpoints from logging #211

This commit is contained in:
Nikolay Kim 2018-05-08 16:30:34 -07:00
parent 47d80382b2
commit 54c33a7aff
2 changed files with 25 additions and 12 deletions

View File

@ -8,6 +8,8 @@
* Send `ErrorNotFound` instead of `ErrorBadRequest` when path extractor fails #214 * Send `ErrorNotFound` instead of `ErrorBadRequest` when path extractor fails #214
* Allow to exclude certain endpoints from logging #211
## 0.6.0 (2018-05-08) ## 0.6.0 (2018-05-08)
* Add route scopes #202 * Add route scopes #202

View File

@ -1,7 +1,7 @@
//! Request logging middleware //! Request logging middleware
use std::collections::HashSet;
use std::env; use std::env;
use std::fmt; use std::fmt::{self, Display, Formatter};
use std::fmt::{Display, Formatter};
use libc; use libc;
use regex::Regex; use regex::Regex;
@ -74,6 +74,7 @@ use middleware::{Finished, Middleware, Started};
/// ///
pub struct Logger { pub struct Logger {
format: Format, format: Format,
exclude: HashSet<String>,
} }
impl Logger { impl Logger {
@ -81,8 +82,15 @@ impl Logger {
pub fn new(format: &str) -> Logger { pub fn new(format: &str) -> Logger {
Logger { Logger {
format: Format::new(format), format: Format::new(format),
exclude: HashSet::new(),
} }
} }
/// Ignore and do not log access info for specified path.
pub fn exclude<T: Into<String>>(mut self, path: T) -> Self {
self.exclude.insert(path.into());
self
}
} }
impl Default for Logger { impl Default for Logger {
@ -94,6 +102,7 @@ impl Default for Logger {
fn default() -> Logger { fn default() -> Logger {
Logger { Logger {
format: Format::default(), format: Format::default(),
exclude: HashSet::new(),
} }
} }
} }
@ -102,21 +111,23 @@ struct StartTime(time::Tm);
impl Logger { impl Logger {
fn log<S>(&self, req: &mut HttpRequest<S>, resp: &HttpResponse) { fn log<S>(&self, req: &mut HttpRequest<S>, resp: &HttpResponse) {
let entry_time = req.extensions().get::<StartTime>().unwrap().0; if let Some(entry_time) = req.extensions().get::<StartTime>() {
let render = |fmt: &mut Formatter| {
let render = |fmt: &mut Formatter| { for unit in &self.format.0 {
for unit in &self.format.0 { unit.render(fmt, req, resp, entry_time.0)?;
unit.render(fmt, req, resp, entry_time)?; }
} Ok(())
Ok(()) };
}; info!("{}", FormatDisplay(&render));
info!("{}", FormatDisplay(&render)); }
} }
} }
impl<S> Middleware<S> for Logger { impl<S> Middleware<S> for Logger {
fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> { fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {
req.extensions_mut().insert(StartTime(time::now())); if !self.exclude.contains(req.path()) {
req.extensions_mut().insert(StartTime(time::now()));
}
Ok(Started::Done) Ok(Started::Done)
} }