tracing_test/
subscriber.rs

1use std::{
2    io,
3    sync::{Mutex, MutexGuard},
4};
5
6use tracing_core::Dispatch;
7use tracing_subscriber::{fmt::MakeWriter, FmtSubscriber};
8
9/// A fake writer that writes into a buffer (behind a mutex).
10#[derive(Debug)]
11pub struct MockWriter<'a> {
12    buf: &'a Mutex<Vec<u8>>,
13}
14
15impl<'a> MockWriter<'a> {
16    /// Create a new `MockWriter` that writes into the specified buffer (behind a mutex).
17    pub fn new(buf: &'a Mutex<Vec<u8>>) -> Self {
18        Self { buf }
19    }
20
21    /// Give access to the internal buffer (behind a `MutexGuard`).
22    fn buf(&self) -> io::Result<MutexGuard<'a, Vec<u8>>> {
23        // Note: The `lock` will block. This would be a problem in production code,
24        // but is fine in tests.
25        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        // Lock target buffer
34        let mut target = self.buf()?;
35
36        // Write to stdout in order to show up in tests
37        print!("{}", String::from_utf8(buf.to_vec()).unwrap());
38
39        // Write to buffer
40        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
56/// Return a new subscriber that writes to the specified [`MockWriter`].
57///
58/// [`MockWriter`]: struct.MockWriter.html
59pub 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}