| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
use std::cell::RefCell; |
| 26 |
use std::io::Write; |
| 27 |
use std::sync::{Arc, Mutex, Once}; |
| 28 |
|
| 29 |
thread_local! { |
| 30 |
|
| 31 |
static SINK: RefCell<Option<Arc<Mutex<Vec<u8>>>>> = const { RefCell::new(None) }; |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
#[derive(Clone)] |
| 37 |
struct ThreadSink; |
| 38 |
|
| 39 |
impl Write for ThreadSink { |
| 40 |
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { |
| 41 |
SINK.with(|sink| { |
| 42 |
if let Some(buffer) = sink.borrow().as_ref() { |
| 43 |
buffer.lock().unwrap().extend_from_slice(buf); |
| 44 |
} |
| 45 |
}); |
| 46 |
Ok(buf.len()) |
| 47 |
} |
| 48 |
|
| 49 |
fn flush(&mut self) -> std::io::Result<()> { |
| 50 |
Ok(()) |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for ThreadSink { |
| 55 |
type Writer = Self; |
| 56 |
fn make_writer(&'a self) -> Self::Writer { |
| 57 |
Self |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
pub(crate) struct Capture(Arc<Mutex<Vec<u8>>>); |
| 63 |
|
| 64 |
impl Capture { |
| 65 |
|
| 66 |
|
| 67 |
pub(crate) fn start() -> Self { |
| 68 |
install(); |
| 69 |
let buffer = Arc::new(Mutex::new(Vec::new())); |
| 70 |
SINK.with(|sink| *sink.borrow_mut() = Some(Arc::clone(&buffer))); |
| 71 |
Self(buffer) |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
pub(crate) fn logged(&self) -> String { |
| 76 |
String::from_utf8(self.0.lock().unwrap().clone()).expect("fmt layer writes utf-8") |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
impl Drop for Capture { |
| 81 |
fn drop(&mut self) { |
| 82 |
SINK.with(|sink| *sink.borrow_mut() = None); |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
fn install() { |
| 87 |
static ONCE: Once = Once::new(); |
| 88 |
ONCE.call_once(|| { |
| 89 |
use tracing_subscriber::layer::SubscriberExt; |
| 90 |
|
| 91 |
let subscriber = tracing_subscriber::registry() |
| 92 |
.with(tracing_subscriber::EnvFilter::new( |
| 93 |
crate::DEFAULT_LOG_FILTER, |
| 94 |
)) |
| 95 |
.with( |
| 96 |
tracing_subscriber::fmt::layer() |
| 97 |
.with_ansi(false) |
| 98 |
.with_writer(ThreadSink), |
| 99 |
); |
| 100 |
|
| 101 |
tracing::subscriber::set_global_default(subscriber) |
| 102 |
.expect("nothing else installs a global subscriber in the test binary"); |
| 103 |
}); |
| 104 |
} |
| 105 |
|