diff --git a/README.md b/README.md index 0e9dc58ae..1ff4a89ba 100644 --- a/README.md +++ b/README.md @@ -158,3 +158,20 @@ test tests::it_adds_one ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured ``` + +## Configuring log target + +By default, `env_logger` logs to stderr. If you want to log to stdout instead, +you can use the `LogBuilder` to change the log target: + +```rust +use std::env; +use env_logger::{LogBuilder, LogTarget}; + +let mut builder = LogBuilder::new(); +builder.target(LogTarget::Stdout); +if env::var("RUST_LOG").is_ok() { + builder.parse(&env::var("RUST_LOG").unwrap()); +} +builder.init().unwrap(); +``` diff --git a/env/src/lib.rs b/env/src/lib.rs index 23710c7fd..7e2f9da7e 100644 --- a/env/src/lib.rs +++ b/env/src/lib.rs @@ -152,11 +152,19 @@ mod filter; #[path = "string.rs"] mod filter; +/// Log target, either stdout or stderr. +#[derive(Debug)] +pub enum LogTarget { + Stdout, + Stderr, +} + /// The logger. pub struct Logger { directives: Vec, filter: Option, format: Box String + Sync + Send>, + target: LogTarget, } /// LogBuilder acts as builder for initializing the Logger. @@ -196,6 +204,7 @@ pub struct LogBuilder { directives: Vec, filter: Option, format: Box String + Sync + Send>, + target: LogTarget, } impl LogBuilder { @@ -208,6 +217,7 @@ impl LogBuilder { format!("{}:{}: {}", record.level(), record.location().module_path(), record.args()) }), + target: LogTarget::Stderr, } } @@ -236,6 +246,14 @@ impl LogBuilder { self } + /// Sets the target for the log output. + /// + /// Env logger can log to either stdout or stderr. The default is stderr. + pub fn target(&mut self, target: LogTarget) -> &mut Self { + self.target = target; + self + } + /// Parses the directives string in the same form as the RUST_LOG /// environment variable. /// @@ -286,6 +304,7 @@ impl LogBuilder { directives: mem::replace(&mut self.directives, Vec::new()), filter: mem::replace(&mut self.filter, None), format: mem::replace(&mut self.format, Box::new(|_| String::new())), + target: mem::replace(&mut self.target, LogTarget::Stderr), } } } @@ -337,7 +356,12 @@ impl Log for Logger { } } - let _ = writeln!(&mut io::stderr(), "{}", (self.format)(record)); + match self.target { + LogTarget::Stdout => println!("{}", (self.format)(record)), + LogTarget::Stderr => { + let _ = writeln!(&mut io::stderr(), "{}", (self.format)(record)); + }, + }; } }