1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#[macro_use]
extern crate lazy_static;
use std::sync::Arc;
mod stable_list;
use stable_list::StableList;
lazy_static! {
static ref _CAPTURE_LOG: Box<Caplog> = {
let handler = Box::new(Caplog {
logs: Arc::new(StableList::new()),
});
log::set_boxed_logger(handler.clone()).unwrap();
log::set_max_level(log::LevelFilter::Trace);
handler
};
}
#[derive(Clone)]
struct Caplog {
logs: Arc<StableList<Record>>,
}
impl log::Log for Caplog {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}
fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
self.logs.push(Record {
level: record.level(),
msg: record.args().to_string(),
})
}
}
fn flush(&self) {}
}
#[derive(Debug)]
pub struct Record {
pub level: log::Level,
pub msg: String,
}
pub struct CaplogHandle {
list: Arc<StableList<Record>>,
}
impl CaplogHandle {
pub fn any_msg_contains(&self, snippet: &str) -> bool {
self.list.iter().any(|rec| dbg!(rec).msg.contains(snippet))
}
}
pub fn get_handle() -> CaplogHandle {
CaplogHandle {
list: _CAPTURE_LOG.logs.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use log::info;
#[test]
fn simple_any_msg_contains() {
let handle = get_handle();
let num_recs = handle.list.len();
info!("logging message");
assert!(handle.list.len() > num_recs);
assert!(handle.any_msg_contains("logging message"));
}
}