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
use std::{
io,
sync::{Mutex, MutexGuard},
};
use tracing_core::Dispatch;
use tracing_subscriber::{fmt::MakeWriter, FmtSubscriber};
#[derive(Debug)]
pub struct MockWriter<'a> {
buf: &'a Mutex<Vec<u8>>,
}
impl<'a> MockWriter<'a> {
pub fn new(buf: &'a Mutex<Vec<u8>>) -> Self {
Self { buf }
}
fn buf(&self) -> io::Result<MutexGuard<'a, Vec<u8>>> {
self.buf
.lock()
.map_err(|_| io::Error::from(io::ErrorKind::Other))
}
}
impl<'a> io::Write for MockWriter<'a> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut target = self.buf()?;
print!("{}", String::from_utf8(buf.to_vec()).unwrap());
target.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.buf()?.flush()
}
}
impl<'a> MakeWriter for MockWriter<'a> {
type Writer = Self;
fn make_writer(&self) -> Self::Writer {
MockWriter::new(self.buf)
}
}
pub fn get_subscriber(mock_writer: MockWriter<'static>, env_filter: &str) -> Dispatch {
FmtSubscriber::builder()
.with_env_filter(env_filter)
.with_writer(mock_writer)
.with_level(true)
.with_ansi(false)
.into()
}