tracing_test/
subscriber.rs1use std::{
2 io,
3 sync::{Mutex, MutexGuard},
4};
5
6use tracing_core::Dispatch;
7use tracing_subscriber::{fmt::MakeWriter, FmtSubscriber};
8
9#[derive(Debug)]
11pub struct MockWriter<'a> {
12 buf: &'a Mutex<Vec<u8>>,
13}
14
15impl<'a> MockWriter<'a> {
16 pub fn new(buf: &'a Mutex<Vec<u8>>) -> Self {
18 Self { buf }
19 }
20
21 fn buf(&self) -> io::Result<MutexGuard<'a, Vec<u8>>> {
23 self.buf
26 .lock()
27 .map_err(|_| io::Error::from(io::ErrorKind::Other))
28 }
29}
30
31impl<'a> io::Write for MockWriter<'a> {
32 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
33 let mut target = self.buf()?;
35
36 print!("{}", String::from_utf8(buf.to_vec()).unwrap());
38
39 target.write(buf)
41 }
42
43 fn flush(&mut self) -> io::Result<()> {
44 self.buf()?.flush()
45 }
46}
47
48impl<'a> MakeWriter<'_> for MockWriter<'a> {
49 type Writer = Self;
50
51 fn make_writer(&self) -> Self::Writer {
52 MockWriter::new(self.buf)
53 }
54}
55
56pub fn get_subscriber(mock_writer: MockWriter<'static>, env_filter: &str) -> Dispatch {
60 FmtSubscriber::builder()
61 .with_env_filter(env_filter)
62 .with_writer(mock_writer)
63 .with_level(true)
64 .with_ansi(false)
65 .into()
66}