diff --git a/examples/proper.rs b/examples/proper.rs index c0432ef..d798355 100644 --- a/examples/proper.rs +++ b/examples/proper.rs @@ -1,12 +1,11 @@ -extern crate slog_stdlog; +extern crate slog_async; extern crate slog_envlogger; -extern crate slog_term; extern crate slog_scope; -extern crate slog_async; +extern crate slog_stdlog; +extern crate slog_term; /// Import longer-name versions of macros only to not collide with legacy `log` -#[macro_use(slog_error, slog_info, slog_trace, slog_log, slog_o, slog_record, - slog_record_static, slog_b, slog_kv)] +#[macro_use(slog_error, slog_info, slog_trace, slog_o)] extern crate slog; use slog::Drain; @@ -15,22 +14,20 @@ use slog::Drain; extern crate log; fn main() { - let drain = - slog_async::Async::default( - slog_envlogger::new( - slog_term::CompactFormat::new( - slog_term::TermDecorator::new() - .stderr().build() - ).build().fuse() - )); + let drain = slog_async::Async::default(slog_envlogger::new( + slog_term::CompactFormat::new(slog_term::TermDecorator::new().stderr().build()) + .build() + .fuse(), + )); - let root_logger = slog::Logger::root(drain.fuse(), - slog_o!("build" => "8jdkj2df", "version" => "0.1.5")); + let root_logger = slog::Logger::root( + drain.fuse(), + slog_o!("build" => "8jdkj2df", "version" => "0.1.5"), + ); slog_stdlog::init().unwrap(); slog_scope::scope(&root_logger, || { - slog_error!(root_logger, "slog error"); error!("log error"); slog_info!(root_logger, "slog info"); diff --git a/examples/scopes.rs b/examples/scopes.rs index 5f2f81a..43cf68c 100644 --- a/examples/scopes.rs +++ b/examples/scopes.rs @@ -1,8 +1,8 @@ -extern crate slog_stdlog; extern crate slog_envlogger; extern crate slog_scope; +extern crate slog_stdlog; -#[macro_use(o, kv)] +#[macro_use(o)] extern crate slog; #[macro_use] @@ -15,7 +15,7 @@ fn main() { slog_scope::scope( &slog_scope::logger().new(o!("scope-extra-data" => "data")), - || foo() + foo, ); trace!("log trace"); @@ -27,7 +27,7 @@ fn foo() { // scopes can be nested! slog_scope::scope( &slog_scope::logger().new(o!("even-more-scope-extra-data" => "data2")), - || bar() + bar, ); } diff --git a/examples/simple.rs b/examples/simple.rs index 3a91608..6f326df 100644 --- a/examples/simple.rs +++ b/examples/simple.rs @@ -1,5 +1,5 @@ -extern crate slog_stdlog; extern crate slog_envlogger; +extern crate slog_stdlog; #[macro_use] extern crate log; diff --git a/src/lib.rs b/src/lib.rs index 1c84c0b..3a2ef4b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -66,20 +66,22 @@ //! warn for hello. In both cases the log message must include a single digit //! number followed by 'scopes'. -#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", - html_favicon_url = "http://www.rust-lang.org/favicon.ico", - html_root_url = "http://doc.rust-lang.org/env_logger/")] +#![doc( + html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "http://www.rust-lang.org/favicon.ico", + html_root_url = "http://doc.rust-lang.org/env_logger/" +)] #![cfg_attr(test, deny(warnings))] +extern crate log; extern crate slog; -extern crate slog_term; -extern crate slog_stdlog; extern crate slog_scope; -extern crate log; +extern crate slog_stdlog; +extern crate slog_term; -use std::{env, result, sync}; -use std::cell::RefCell; use slog::*; +use std::cell::RefCell; +use std::{env, result, sync}; #[cfg(feature = "regex")] #[path = "regex.rs"] @@ -94,8 +96,8 @@ thread_local! { } /// `EnvLogger` drain. -pub struct EnvLogger { - drain : T, +pub struct EnvLogger { + drain: T, directives: Vec, filter: Option, } @@ -103,17 +105,17 @@ pub struct EnvLogger { /// LogBuilder acts as builder for initializing the EnvLogger. /// It can be used change the enviromental variable used /// to provide the logging directives and also set the default log level filter. -pub struct LogBuilder { - drain : T, +pub struct LogBuilder { + drain: T, directives: Vec, filter: Option, } -impl LogBuilder { +impl LogBuilder { /// Initializes the log builder with defaults - pub fn new(d : T) -> Self { + pub fn new(d: T) -> Self { LogBuilder { - drain : d, + drain: d, directives: Vec::new(), filter: None, } @@ -123,12 +125,10 @@ impl LogBuilder { /// /// The given module (if any) will log at most the specified level provided. /// If no module is provided then the filter will apply to all log messages. - pub fn filter(mut self, - module: Option<&str>, - level: FilterLevel) -> Self { + pub fn filter(mut self, module: Option<&str>, level: FilterLevel) -> Self { self.directives.push(LogDirective { name: module.map(|s| s.to_string()), - level: level, + level, }); self } @@ -173,15 +173,15 @@ impl LogBuilder { } = self; EnvLogger { - drain: drain, - directives: directives, - filter: filter, + drain, + directives, + filter, } } } -impl EnvLogger { - pub fn new(d : T) -> Self { +impl EnvLogger { + pub fn new(d: T) -> Self { let mut builder = LogBuilder::new(d); if let Ok(s) = env::var("RUST_LOG") { @@ -192,8 +192,10 @@ impl EnvLogger { } pub fn filter(&self) -> FilterLevel { - self.directives.iter() - .map(|d| d.level).max() + self.directives + .iter() + .map(|d| d.level) + .max() .unwrap_or(FilterLevel::Off) } @@ -201,28 +203,28 @@ impl EnvLogger { // Search for the longest match, the vector is assumed to be pre-sorted. for directive in self.directives.iter().rev() { match directive.name { - Some(ref name) if !module.starts_with(&**name) => {}, - Some(..) | None => { - return level.as_usize() <= directive.level.as_usize() - } + Some(ref name) if !module.starts_with(&**name) => {} + Some(..) | None => return level.as_usize() <= directive.level.as_usize(), } } false } } -impl Drain for EnvLogger -where T : Drain { +impl Drain for EnvLogger +where + T: Drain, +{ type Err = T::Err; type Ok = (); - fn log(&self, info: &Record, val : &OwnedKVList) -> result::Result<(), T::Err> { + fn log(&self, info: &Record, val: &OwnedKVList) -> result::Result<(), T::Err> { if !self.enabled(info.level(), info.module()) { return Ok(()); } if let Some(filter) = self.filter.as_ref() { if !filter.is_match(&format!("{}", info.msg())) { - return Ok(()) + return Ok(()); } } @@ -241,7 +243,7 @@ struct LogDirective { } /// Create a `EnvLogger` using `RUST_LOG` environment variable -pub fn new(d : T) -> EnvLogger { +pub fn new(d: T) -> EnvLogger { let mut builder = LogBuilder::new(d); if let Ok(s) = env::var("RUST_LOG") { @@ -261,9 +263,8 @@ pub fn new(d : T) -> EnvLogger { /// anything that `slog` has to offer, so I highly encourage to use `new()` /// instead and explicitly configure your loggers. pub fn init() -> std::result::Result { - let drain = slog_term::CompactFormat::new( - slog_term::TermDecorator::new().stderr().build() - ).build(); + let drain = + slog_term::CompactFormat::new(slog_term::TermDecorator::new().stderr().build()).build(); let drain = new(drain); let drain = sync::Mutex::new(drain.fuse()); @@ -282,64 +283,75 @@ fn parse_logging_spec(spec: &str) -> (Vec, Option) let mods = parts.next(); let filter = parts.next(); if parts.next().is_some() { - println!("warning: invalid logging spec '{}', \ - ignoring it (too many '/'s)", spec); + println!( + "warning: invalid logging spec '{}', \ + ignoring it (too many '/'s)", + spec + ); return (dirs, None); } - mods.map(|m| { for s in m.split(',') { - if s.len() == 0 { continue } - let mut parts = s.split('='); - let (log_level, name) = match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) { - (Some(part0), None, None) => { - // if the single argument is a log-level string or number, - // treat that as a global fallback - match part0.parse() { - Ok(num) => (num, None), - Err(_) => (FilterLevel::max(), Some(part0)), - } + + if let Some(m) = mods { + for s in m.split(',') { + if s.is_empty() { + continue; } - (Some(part0), Some(""), None) => (FilterLevel::max(), Some(part0)), - (Some(part0), Some(part1), None) => { - match part1.parse() { - Ok(num) => (num, Some(part0)), + let mut parts = s.split('='); + let (log_level, name) = + match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) { + (Some(part0), None, None) => { + // if the single argument is a log-level string or number, + // treat that as a global fallback + match part0.parse() { + Ok(num) => (num, None), + Err(_) => (FilterLevel::max(), Some(part0)), + } + } + (Some(part0), Some(""), None) => (FilterLevel::max(), Some(part0)), + (Some(part0), Some(part1), None) => match part1.parse() { + Ok(num) => (num, Some(part0)), + _ => { + println!( + "warning: invalid logging spec '{}', \ + ignoring it", + part1 + ); + continue; + } + }, _ => { - println!("warning: invalid logging spec '{}', \ - ignoring it", part1); - continue + println!( + "warning: invalid logging spec '{}', \ + ignoring it", + s + ); + continue; } - } - }, - _ => { - println!("warning: invalid logging spec '{}', \ - ignoring it", s); - continue - } - }; - dirs.push(LogDirective { - name: name.map(|s| s.to_string()), - level: log_level, - }); - }}); - - let filter = filter.map_or(None, |filter| { - match filter::Filter::new(filter) { - Ok(re) => Some(re), - Err(e) => { - println!("warning: invalid regex filter - {}", e); - None - } + }; + dirs.push(LogDirective { + name: name.map(|s| s.to_string()), + level: log_level, + }); + } + }; + + let filter = filter.and_then(|filter| match filter::Filter::new(filter) { + Ok(re) => Some(re), + Err(e) => { + println!("warning: invalid regex filter - {}", e); + None } }); - return (dirs, filter); + (dirs, filter) } #[cfg(test)] mod tests { - use slog::{Level, FilterLevel}; use super::slog; + use slog::{FilterLevel, Level}; - use super::{LogBuilder, EnvLogger, LogDirective, parse_logging_spec}; + use super::{parse_logging_spec, EnvLogger, LogBuilder, LogDirective}; fn make_logger(dirs: Vec) -> EnvLogger { let mut logger = LogBuilder::new(slog::Discard).build(); @@ -349,7 +361,9 @@ mod tests { #[test] fn filter_info() { - let logger = LogBuilder::new(slog::Discard).filter(None, FilterLevel::Info).build(); + let logger = LogBuilder::new(slog::Discard) + .filter(None, FilterLevel::Info) + .build(); assert!(logger.enabled(Level::Info, "crate1")); assert!(!logger.enabled(Level::Debug, "crate1")); } @@ -357,17 +371,19 @@ mod tests { #[test] fn filter_beginning_longest_match() { let logger = LogBuilder::new(slog::Discard) - .filter(Some("crate2"), FilterLevel::Info) - .filter(Some("crate2::mod"), FilterLevel::Debug) - .filter(Some("crate1::mod1"), FilterLevel::Warning) - .build(); + .filter(Some("crate2"), FilterLevel::Info) + .filter(Some("crate2::mod"), FilterLevel::Debug) + .filter(Some("crate1::mod1"), FilterLevel::Warning) + .build(); assert!(logger.enabled(Level::Debug, "crate2::mod1")); assert!(!logger.enabled(Level::Debug, "crate2")); } #[test] fn parse_default() { - let logger = LogBuilder::new(slog::Discard).parse("info,crate1::mod1=warn").build(); + let logger = LogBuilder::new(slog::Discard) + .parse("info,crate1::mod1=warn") + .build(); assert!(logger.enabled(Level::Warning, "crate1::mod1")); assert!(logger.enabled(Level::Info, "crate2::mod2")); } @@ -377,12 +393,12 @@ mod tests { let logger = make_logger(vec![ LogDirective { name: Some("crate2".to_string()), - level: FilterLevel::Info + level: FilterLevel::Info, }, LogDirective { name: Some("crate1::mod1".to_string()), - level: FilterLevel::Warning - } + level: FilterLevel::Warning, + }, ]); assert!(logger.enabled(Level::Warning, "crate1::mod1")); assert!(!logger.enabled(Level::Info, "crate1::mod1")); @@ -393,8 +409,14 @@ mod tests { #[test] fn no_match() { let logger = make_logger(vec![ - LogDirective { name: Some("crate2".to_string()), level: FilterLevel::Info }, - LogDirective { name: Some("crate1::mod1".to_string()), level: FilterLevel::Warning } + LogDirective { + name: Some("crate2".to_string()), + level: FilterLevel::Info, + }, + LogDirective { + name: Some("crate1::mod1".to_string()), + level: FilterLevel::Warning, + }, ]); assert!(!logger.enabled(Level::Warning, "crate3")); } @@ -402,8 +424,14 @@ mod tests { #[test] fn match_beginning() { let logger = make_logger(vec![ - LogDirective { name: Some("crate2".to_string()), level: FilterLevel::Info }, - LogDirective { name: Some("crate1::mod1".to_string()), level: FilterLevel::Warning } + LogDirective { + name: Some("crate2".to_string()), + level: FilterLevel::Info, + }, + LogDirective { + name: Some("crate1::mod1".to_string()), + level: FilterLevel::Warning, + }, ]); assert!(logger.enabled(Level::Info, "crate2::mod1")); } @@ -411,9 +439,18 @@ mod tests { #[test] fn match_beginning_longest_match() { let logger = make_logger(vec![ - LogDirective { name: Some("crate2".to_string()), level: FilterLevel::Info }, - LogDirective { name: Some("crate2::mod".to_string()), level: FilterLevel::Debug }, - LogDirective { name: Some("crate1::mod1".to_string()), level: FilterLevel::Warning } + LogDirective { + name: Some("crate2".to_string()), + level: FilterLevel::Info, + }, + LogDirective { + name: Some("crate2::mod".to_string()), + level: FilterLevel::Debug, + }, + LogDirective { + name: Some("crate1::mod1".to_string()), + level: FilterLevel::Warning, + }, ]); assert!(logger.enabled(Level::Debug, "crate2::mod1")); assert!(!logger.enabled(Level::Debug, "crate2")); @@ -422,8 +459,14 @@ mod tests { #[test] fn match_default() { let logger = make_logger(vec![ - LogDirective { name: None, level: FilterLevel::Info }, - LogDirective { name: Some("crate1::mod1".to_string()), level: FilterLevel::Warning } + LogDirective { + name: None, + level: FilterLevel::Info, + }, + LogDirective { + name: Some("crate1::mod1".to_string()), + level: FilterLevel::Warning, + }, ]); assert!(logger.enabled(Level::Warning, "crate1::mod1")); assert!(logger.enabled(Level::Info, "crate2::mod2")); @@ -432,8 +475,14 @@ mod tests { #[test] fn zero_level() { let logger = make_logger(vec![ - LogDirective { name: None, level: FilterLevel::Info }, - LogDirective { name: Some("crate1::mod1".to_string()), level: FilterLevel::Off } + LogDirective { + name: None, + level: FilterLevel::Info, + }, + LogDirective { + name: Some("crate1::mod1".to_string()), + level: FilterLevel::Off, + }, ]); assert!(!logger.enabled(Level::Error, "crate1::mod1")); assert!(logger.enabled(Level::Info, "crate2::mod2")); diff --git a/src/regex.rs b/src/regex.rs index 0df03e6..056b0a8 100644 --- a/src/regex.rs +++ b/src/regex.rs @@ -10,7 +10,7 @@ pub struct Filter { impl Filter { pub fn new(spec: &str) -> Result { - match Regex::new(spec){ + match Regex::new(spec) { Ok(r) => Ok(Filter { inner: r }), Err(e) => Err(e.to_string()), } diff --git a/src/string.rs b/src/string.rs index 74d0e04..0762e89 100644 --- a/src/string.rs +++ b/src/string.rs @@ -6,7 +6,9 @@ pub struct Filter { impl Filter { pub fn new(spec: &str) -> Result { - Ok(Filter { inner: spec.to_string() }) + Ok(Filter { + inner: spec.to_string(), + }) } pub fn is_match(&self, s: &str) -> bool { diff --git a/tests/regexp_filter.rs b/tests/regexp_filter.rs index 0ca2f87..40dc564 100644 --- a/tests/regexp_filter.rs +++ b/tests/regexp_filter.rs @@ -1,8 +1,9 @@ -#[macro_use] extern crate log; +#[macro_use] +extern crate log; extern crate slog_envlogger; -use std::process; use std::env; +use std::process; use std::str; fn main() { @@ -14,7 +15,7 @@ fn main() { } fn child_main() { - let _guard =slog_envlogger::init().unwrap(); + let _guard = slog_envlogger::init().unwrap(); info!("XYZ Message"); } @@ -25,7 +26,9 @@ fn run_child(rust_log: String) -> bool { .env("RUST_LOG", rust_log) .output() .unwrap_or_else(|e| panic!("Unable to start child process: {}", e)); - str::from_utf8(out.stderr.as_ref()).unwrap().contains("XYZ Message") + str::from_utf8(out.stderr.as_ref()) + .unwrap() + .contains("XYZ Message") } fn assert_message_printed(rust_log: &str) { @@ -36,7 +39,10 @@ fn assert_message_printed(rust_log: &str) { fn assert_message_not_printed(rust_log: &str) { if run_child(rust_log.to_string()) { - panic!("RUST_LOG={} should not allow the test log message", rust_log) + panic!( + "RUST_LOG={} should not allow the test log message", + rust_log + ) } }