Skip to main content

server/
log_capture.rs

1//! Capturing what the tracing subscriber writes, for tests asserting log lines.
2
3use std::sync::{Arc, Mutex};
4
5/// A tracing sink that keeps what the subscriber wrote.
6#[derive(Clone, Default)]
7pub struct Captured(Arc<Mutex<Vec<u8>>>);
8
9impl std::io::Write for Captured {
10    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
11        if let Ok(mut buf) = self.0.lock() {
12            buf.extend_from_slice(bytes);
13        }
14        Ok(bytes.len())
15    }
16
17    fn flush(&mut self) -> std::io::Result<()> {
18        Ok(())
19    }
20}
21
22impl Captured {
23    pub fn error_lines(&self) -> usize {
24        let buf = self.0.lock().map(|buf| buf.clone()).unwrap_or_default();
25        String::from_utf8_lossy(&buf)
26            .lines()
27            .filter(|line| line.contains("ERROR"))
28            .count()
29    }
30
31    pub fn subscriber(&self) -> impl tracing::Subscriber + Send + Sync + 'static {
32        let writer = self.clone();
33        tracing_subscriber::fmt()
34            .with_writer(move || writer.clone())
35            .finish()
36    }
37}