I have some code with logging, and when running cargo test
, I'd like to have the log messages hidden unless I do cargo test -- --nocapture
. So I'd like to have a logger which does "println!" to standard output and nothing more or less - no buffering, no sending some stuff to stderr, etc. The default logger somehow escapes whatever mechanism cargo test
uses to capture and hide output, so I get unwanted output for successful logs. How can I suppress that?
struct TestLogger;
impl std::io::Write for TestLogger {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
print!("{}", std::str::from_utf8(buf).unwrap());
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn test() {
simplelog::WriteLogger::init(log::LevelFilter::Error, Default::default(), TestLogger)
.expect("log initialization failed");
log::error!("error");
}
$ cargo t -- --nocapture
running 1 test
test test ... 08:13:19 [ERROR] error
ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
$ cargo t
running 1 test
test test ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
or simply test-log — Rust testing library // Lib.rs which uses env_logger or tracing though.
test_log suggests
let _ = env_logger::builder().is_test(true).try_init();
which seems promising. Have to try that. I'm looking for a one-liner I can put in unit tests.