1
//! Capturing what the tracing subscriber writes, for tests asserting log lines.
2

            
3
use std::sync::{Arc, Mutex};
4

            
5
/// A tracing sink that keeps what the subscriber wrote.
6
#[derive(Clone, Default)]
7
pub struct Captured(Arc<Mutex<Vec<u8>>>);
8

            
9
impl std::io::Write for Captured {
10
903
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
11
903
        if let Ok(mut buf) = self.0.lock() {
12
903
            buf.extend_from_slice(bytes);
13
        }
14
903
        Ok(bytes.len())
15
903
    }
16

            
17
    fn flush(&mut self) -> std::io::Result<()> {
18
        Ok(())
19
    }
20
}
21

            
22
impl Captured {
23
1445
    pub fn error_lines(&self) -> usize {
24
1445
        let buf = self.0.lock().map(|buf| buf.clone()).unwrap_or_default();
25
1445
        String::from_utf8_lossy(&buf)
26
1445
            .lines()
27
903
            .filter(|line| line.contains("ERROR"))
28
            .count()
29
1445
    }
30

            
31
1265
    pub fn subscriber(&self) -> impl tracing::Subscriber + Send + Sync + 'static {
32
1265
        let writer = self.clone();
33
1265
        tracing_subscriber::fmt()
34
903
            .with_writer(move || writer.clone())
35
            .finish()
36
1265
    }
37
}