How to initialize the logger for integration tests?

For now, you can just re-initialize the logger at the top of every test and ignore the error. It's not a pretty solution but it works and is perfectly safe.

let _ = env_logger::init();

// your test code...

In addition to Danilo Bargen's comment, you can write it in a shorter form:

use std::sync::Once;

static INIT: Once = Once::new();

fn setup() {
  INIT.call_once(env_logger::init);
}

You can use something like this:

use std::sync::Once;

static INIT: Once = Once::new();

/// Setup function that is only run once, even if called multiple times.
fn setup() {
    INIT.call_once(|| {
        env_logger::init().unwrap();
    });
}

Then simply call setup() in the beginning of each test.

Originally based on this blogpost.


The latest documentation has a recommendation:

#[cfg(test)]
mod tests {
    fn init() {
        let _ = env_logger::builder().is_test(true).try_init();
    }

    #[test]
    fn it_works() {
        init();
        info!("This record will be captured by `cargo test`");

        assert_eq!(3, 1 + 2);
    }
}

Tags:

Rust