fern icon indicating copy to clipboard operation
fern copied to clipboard

Capture logs inside tests?

Open sourcefrog opened this issue 5 years ago • 2 comments

Hi,

It would be great if tests could be written to the tests's stdout, and then (by default) shown only if the test fails.

It looks like .chain(std::io::stdout()) sends them to the process's real stdout, bypassing the test framework's hooks. I see there's a lot of history on this in https://github.com/rust-lang/rust/issues/42474 and perhaps it's not possible for Fern to fix? But it seems like if println! is captured, at least Fern could simply do println! for everything.

Or perhaps this is possible already and I'm just missing it, and if so perhaps it could be clearer in the docs?

sourcefrog avatar Apr 26 '20 22:04 sourcefrog

It seems something like this will work. If there's no simpler way could I suggest this be added to the examples?


fn install_test_logger() {
    // This'll fail if called twice; don't worry.
    let _ = fern::Dispatch::new()
        // ...
        .level(log::LevelFilter::Debug)
        .chain(fern::Output::call(|record| println!("{}", record.args())))
        .apply();
}```

sourcefrog avatar Apr 26 '20 22:04 sourcefrog

Thanks! I hadn't realized that the test framework's hook was per-thread rather than global. Makes sense now that I think about it, though.

Adding that as an example sounds like a good idea. It might also be worth adding to this note as well (or we could just remove the stdout from this example; it isn't really relevant): https://github.com/daboross/fern/blob/6666bd24f1b7aa3522746a0fc2407b0680e6ff80/src/builders.rs#L691-L701.

daboross avatar May 11 '20 12:05 daboross