4

My application is using the tracing Rust crate to create log output. How do I print these log messages when I'm running my tests?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48

3 Answers3

4

You can use the tracing_test Rust crate for this. It works like this:

#[traced_test]
#[test]
fn plain_old_test() {
   ...
}

All you have to do is add the tracing_test to your list of dependencies and decorate your tests with the #[traced_test] macro.

This also works with tokio_macros tests, that are decorated with #[tokio::test].

Then, as @Yuri mentions, you need to run the tests with the --nocapture argument: cargo t --nocapture. This is only relevant if the test succeeds.

Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48
  • 2
    It is important to note here that traced_test saves all log output to ram. I was confused why my tests, whose application produces lots of very verbose logs for debugging, was constantly increasing in memory usage to the point of getting OOM killed. – Karibiusk Apr 28 '23 at 16:04
3

Usually, if you need to print the output inside the tests you use --nocapture flag with the cargo test command:

$ cargo test -- --nocapture

Can you test if it works in your case?

Yury
  • 20,618
  • 7
  • 58
  • 86
0

You can use the test-log crate. It works by overriding the #[test] attribute macro, allowing you to include tracing logs seamlessly into your test runs. This means you can see the log output without the need to modify each individual test. Unlike some alternative crates, which may require adding extra lines of code to each test, which is equivalent to calling a self-defined singleton for the tracing init in each test.

LeChatP
  • 33
  • 5
  • Haven't tried this but it sounds superior to my solution that requires you to add the attribute `#[traced_test]` to each test. – Thorkil Værge Aug 23 '23 at 07:45