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()
}