16

I have some tests which use info! from Rust's log crate. I tried:

RUST_LOG=all cargo test -- --nocapture my_tests

but the logs simply won't come out.

I didn't init the logger though, because puttin env_logger::init(); won't work:

failed to resolve: use of undeclared crate or module `env_logger`
Gatonito
  • 1,662
  • 5
  • 26
  • 55
  • You need to init the logger if you want the tests to be printed. If `env_logger` doesn't work, perhaps you're missing the requisite line in `Cargo.toml`, under dev-dependencies? – user4815162342 Apr 14 '21 at 09:24

1 Answers1

25

You may try to use one of several workarounds.

First is to use println when crate is compiled for test like this.

#[cfg(not(test))] 
use log::{info, warn}; // Use log crate when building application
 
#[cfg(test)]
use std::{println as info, println as warn}; // Workaround to use prinltn! for logs.

To prevent cargo from silencing tests stdout, run tests like this

$ cargo test -- --nocapture

Another elegant workaround is to use test-log crate

#[test_log::test] // Automatically wraps test to initialize logging
fn hello_log_tests() {
  // ...
}

To use dependency (such as env_logger mentioned in error message) for tests include it in dev-dependencies section

[dev-dependencies]
env_logger = "*"
m4tx
  • 4,139
  • 5
  • 37
  • 61
Inline
  • 2,566
  • 1
  • 16
  • 32
  • I like the first solution very much, but `info!` sometimes have 3 parameters, the first one being a target. Is it possible to simulate this too? – Gatonito Apr 22 '21 at 21:46
  • You seem like you know more about logging within Rust tests than most people. I'd love if you could take a look at https://stackoverflow.com/q/73293801/470749 Thanks! – Ryan Aug 11 '22 at 19:00
  • 1
    @Inline [test-env-log](https://crates.io/crates/test-env-log) was renamed in [test-log](https://crates.io/crates/test-log) by its author. – ndclt Nov 06 '22 at 13:41