Search code examples
testingrustbenchmarkingrust-criterion

Add logs to cargo bench


I'm using the criterion library to benchmark some code and am in need of printing logs via the log crate. I ran the following command on this snippet of code:

cargo bench --bench my_benchmark

warn!("Please warn");
println!("Please print");

But surprisingly found that my output looked like this:

Please print

At first when I wasn't seeing logs I figured I was missing the --nocapture flag based on a similar question asked on SO on adding logs to unit tests and the criterion docs. This had no effect. Neither did adding the RUST_LOG parameter.

# Same output as above
cargo bench --bench my_benchmark -- --nocapture

# Same output as above
RUST_LOG=debug cargo bench --bench my_benchmark

I don't know if I'm missing something obvious from a crate feature or if this is possible at all. Any help would greatly improve my time to debug. Thank you!


Solution

  • Simply add the logger initialization to each benchmark.

    use log::warn; 
    
    env_logger::builder().is_test(true).try_init().unwrap();
    warn!("This prints");