Test log output not visible in vs code

I'm using rust-lang.rust-analyzer in vs code and want to see a test output in the console.
I have the following code:

#[cfg(test)]
mod tests {

    fn init() {
        let _ = env_logger::builder()
            .target(env_logger::Target::Stdout)
            .filter_level(log::LevelFilter::Off)
            .is_test(true)
            .try_init();
    }

    #[test]
    fn test_listen() {
        init();

In the function under test I have log::debug! and log::info! entries, which don't show up in the output.
What am I missing?

Test output is not printed unless the test fails.

Try making the test fail, or pass --nocapture to the cargo test command.

Doesn't this tell the logger to disable all logging? You probably meant filter_level(log::LevelFilter::Trace).

1 Like

I think LevelFilter::Off means no filter, i.e. show every level. At least this is how I'd interpret the docs:

Off

A level lower than all log levels.

I think the lowest log level would be Trace and the highest Error. But I could be mixing the direction lowest to highest up. Anyway, I never tried it for myself, so only guesswork anyways.

Never mind, you are right.

Thanks for the answers! I changed to LevelFilter::Trace, arg --nocapture seems to be by default there when running a test using the extension.
Is it that the test needs to be over to get the output? I still can't get any and I run into deadlock in my code.

I tried sleeping after a log::debug! as well as a busy loop and in both cases the log output was visible immediately, without waiting for the test to end

#[cfg(test)]
mod tests {
    use std::time::Duration;

    fn init() {
        let _ = env_logger::builder()
            .target(env_logger::Target::Stdout)
            .filter_level(log::LevelFilter::Trace)
            .is_test(true)
            .try_init();
    }

    #[test]
    fn test_listen() {
        init();

        log::debug!("Hi");

        std::thread::sleep(Duration::from_secs(10));
    }
}
running 1 test
[2023-04-24T17:41:51Z DEBUG main::tests] Hi
test tests::test_listen ... ok

To be clear, the tests were run with rust analyzer in VSCode

1 Like

I restarted vs code and can see the output now, I'm not sure why I couldn't see it before (having LevelFilter::Trace). Anyway, thanks for help!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.