|
| 1 | +use std::{io, str, sync::Mutex}; |
| 2 | + |
| 3 | +use tracing::subscriber::set_global_default; |
| 4 | +use tracing_subscriber::{layer::SubscriberExt, registry}; |
| 5 | + |
| 6 | +use tracing_tree::HierarchicalLayer; |
| 7 | + |
| 8 | +struct RecursiveWriter(Mutex<Vec<u8>>); |
| 9 | + |
| 10 | +impl io::Write for &RecursiveWriter { |
| 11 | + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 12 | + self.0.lock().unwrap().extend(buf); |
| 13 | + |
| 14 | + tracing::error!("Nobody expects the Spanish Inquisition"); |
| 15 | + |
| 16 | + Ok(buf.len()) |
| 17 | + } |
| 18 | + |
| 19 | + fn flush(&mut self) -> io::Result<()> { |
| 20 | + tracing::error!("Nobody expects the Spanish Inquisition"); |
| 21 | + Ok(()) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +/// This test checks that if `tracing` events happen during processing of |
| 26 | +/// `on_event`, the library does not deadlock. |
| 27 | +#[test] |
| 28 | +fn recursive_event() { |
| 29 | + static WRITER: RecursiveWriter = RecursiveWriter(Mutex::new(Vec::new())); |
| 30 | + |
| 31 | + let subscriber = registry().with(HierarchicalLayer::new(2).with_writer(|| &WRITER)); |
| 32 | + // This has to be its own integration test because we can't just set a |
| 33 | + // global default like this otherwise and not expect everything else to |
| 34 | + // break. |
| 35 | + set_global_default(subscriber).unwrap(); |
| 36 | + |
| 37 | + tracing::error!("We can never expect the unexpected."); |
| 38 | + |
| 39 | + let output = WRITER.0.lock().unwrap(); |
| 40 | + let output = str::from_utf8(&output).unwrap(); |
| 41 | + |
| 42 | + // If this test finished we're happy. Let's just also check that we did |
| 43 | + // in fact log _something_ and that the logs from within the writer did |
| 44 | + // not actually go through. |
| 45 | + assert!(output.contains("We can never expect the unexpected.")); |
| 46 | + assert!(!output.contains("Nobody expects the Spanish Inquisition")); |
| 47 | +} |
0 commit comments