#tracing #tracing-subscriber #log #insta #test #memory-buffer

tracing-collector

A tracing subscriber that collects a copy of the traces for use in tests with insta snapshots

3 releases

0.1.2 Feb 6, 2023
0.1.1 Feb 5, 2023
0.1.0 Feb 5, 2023

#569 in Testing

Download history 31/week @ 2024-03-09 3/week @ 2024-03-16 62/week @ 2024-03-30 44/week @ 2024-04-06 97/week @ 2024-04-13 22/week @ 2024-04-20 39/week @ 2024-04-27 3/week @ 2024-05-04 3/week @ 2024-05-11 37/week @ 2024-05-18 52/week @ 2024-05-25 68/week @ 2024-06-01 116/week @ 2024-06-08 85/week @ 2024-06-15 40/week @ 2024-06-22

331 downloads per month

MIT license

10KB
113 lines

crates.io

TracingCollector

TracingCollector creates a tracing subscriber that collects a copy of all traces into a buffer. These traces can be retrieved by calling its Display implementation, i.e. calling log.to_string() or format!("{log}"). This is useful for testing with insta snapshots.

IMPORTANT! TracingCollector is meant for use when testing. It collects logs into a memory buffer which keeps growing until it is read, the program exits or it is dropped. This means that if you are using TracingCollector in production the program will eventually run out of memory.

When the TracingCollector is dropped, the buffer is emptied and the tracing subscriber is released but the memory equivalent of a Mutex and an empty Vec is leaked.

When reading the traces, they are stripped of ANSI escape codes and prefixed with a character. The former allows the use of colored & formatted terminal output when the test fails or is run with --nocapture and the latter makes the insta inline snapshots work since rust's r### raw string literals strips leading whitespace. The prefix can be changed or removed using the set_prefix and remove_prefix methods.

Example

#[test]
fn test_logs() {
    let log = TracingCollector::init_debug_level();
    tracing::info!("First log");

    insta::assert_display_snapshot!(log, @r###"
    ㏒   INFO  First log
        at tests/test.rs:6

    "###);

    tracing::debug!("Second log");
    tracing::info!("Third log");

    insta::assert_display_snapshot!(log, @r###"
    ㏒  DEBUG  Second log
        at tests/test.rs:14

      INFO  Third log
       at tests/test.rs:15

   "###);
}

Dependencies

~1.5MB
~27K SLoC