Permalink
Browse files

Make log target configurable

Right now `env_logger` always logs to stderr. This might be
undesireable in some cases.

This commit adds a way to configure the log target. It can be set to
stdout if desired.

Note that writing to stdout is implemented with `println!` instead of
`writeln!`, so that the output is properly captured in tests.
  • Loading branch information...
dbrgn committed Mar 29, 2017
1 parent 25e349c commit a16173429dab789407328b682c3db30d84c5a03c
Showing with 42 additions and 1 deletion.
  1. +17 −0 README.md
  2. +25 −1 env/src/lib.rs
View
@@ -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();
```
View
@@ -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<LogDirective>,
filter: Option<filter::Filter>,
format: Box<Fn(&LogRecord) -> String + Sync + Send>,
target: LogTarget,
}
/// LogBuilder acts as builder for initializing the Logger.
@@ -196,6 +204,7 @@ pub struct LogBuilder {
directives: Vec<LogDirective>,
filter: Option<filter::Filter>,
format: Box<Fn(&LogRecord) -> 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));
},
};
}
}

0 comments on commit a161734

Please sign in to comment.