|
2 | 2 |
|
3 | 3 | A Rust crate for capturing application log output for integration testing. |
4 | 4 |
|
5 | | -Crate: https://crates.io/crates/logcap |
| 5 | +The logger can have a _threaded_ scope to capture logs from a thread, or with a _process_ scope to capture across all threads. |
6 | 6 |
|
7 | | -Docs: https://docs.rs/logcap/latest/logcap |
| 7 | +See the [documentation](https://docs.rs/logcap/latest/logcap). |
| 8 | + |
| 9 | +## Examples |
| 10 | + |
| 11 | +### Capture logs within a single thread |
| 12 | + |
| 13 | +```rust |
| 14 | +use logcap::CaptureScope; |
| 15 | +use log::{info,LevelFilter}; |
| 16 | + |
| 17 | +#[test] |
| 18 | +fn test_logs() { |
| 19 | + logcap::setup(); |
| 20 | + |
| 21 | + // test logic outputting logs |
| 22 | + info!("foobar"); |
| 23 | + |
| 24 | + // make assertions on logs |
| 25 | + logcap::consume(|logs| { |
| 26 | + assert_eq!(1, logs.len()); |
| 27 | + assert_eq!("foobar", logs[0].body); |
| 28 | + }); |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +### Capture logs across threads |
| 33 | +Run tests with `--test_threads=1` to avoid clobbering logs between tests, or use a mutex for synchronization. |
| 34 | + |
| 35 | +```rust |
| 36 | +use logcap::CaptureScope; |
| 37 | +use log::{LevelFilter,warn}; |
| 38 | + |
| 39 | +#[test] |
| 40 | +fn test_logs() { |
| 41 | + logcap::builder() |
| 42 | + .scope(CaptureScope::Process) |
| 43 | + .max_level(LevelFilter::Trace) |
| 44 | + .setup(); |
| 45 | + |
| 46 | + // test multi-threaded logic outputting logs |
| 47 | + warn!("warning from main thread"); |
| 48 | + let _ = thread::spawn(|| warn!("warning from thread 1")).join(); |
| 49 | + let _ = thread::spawn(|| warn!("warning from thread 2")).join(); |
| 50 | + |
| 51 | + // make assertions on logs |
| 52 | + logcap::consume(|logs| { |
| 53 | + assert_eq!(3, logs.len()); |
| 54 | + assert!(logs.iter.find(|log| log.body.contains("thread 1")).is_some()); |
| 55 | + assert!(logs.iter.find(|log| log.body.contains("thread 2")).is_some()); |
| 56 | + assert!(logs.iter.find(|log| log.body.contains("main thread")).is_some()); |
| 57 | + }); |
| 58 | +} |
| 59 | +``` |
0 commit comments