What are ways to run Rust cargo test and have the test runner display any log output to the console stdout or stderr?

Viewed 2475

I've learned:

  • cargo test -- --nocapture which tells Cargo to show output instead of hiding output; I'm interested in seeing output for successful tests, not just failed tests.
  • env_logger crate which enables using an environment variable to set the log level.

I'm seeking any similar ways, and ideally any official reference guide that shows good ways to accomplish this.

1 Answers

Here's one solution that is working for me.

Cargo.toml dependency:

env_logger = "*"

Demo source code:

use log::*;

pub fn foo() -> bool {
    info!("hello world");
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use env_logger;
    #[test]
    fn test_foo() {
        env_logger::init();
        assert!(foo());
    }
}

Command:

RUST_LOG=info cargo test -- --nocapture   
Related