Skip to content

Commit ae5e781

Browse files
committed
chore: add examples to readme
1 parent 9888a46 commit ae5e781

File tree

1 file changed

+54
-2
lines changed

1 file changed

+54
-2
lines changed

README.md

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,58 @@
22

33
A Rust crate for capturing application log output for integration testing.
44

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.
66

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

Comments
 (0)