File: recursive_event.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (47 lines) | stat: -rw-r--r-- 1,606 bytes parent folder | download | duplicates (6)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::{io, str, sync::Mutex};

use tracing::subscriber::set_global_default;
use tracing_subscriber::{layer::SubscriberExt, registry};

use tracing_tree::HierarchicalLayer;

struct RecursiveWriter(Mutex<Vec<u8>>);

impl io::Write for &RecursiveWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.lock().unwrap().extend(buf);

        tracing::error!("Nobody expects the Spanish Inquisition");

        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        tracing::error!("Nobody expects the Spanish Inquisition");
        Ok(())
    }
}

/// This test checks that if `tracing` events happen during processing of
/// `on_event`, the library does not deadlock.
#[test]
fn recursive_event() {
    static WRITER: RecursiveWriter = RecursiveWriter(Mutex::new(Vec::new()));

    let subscriber = registry().with(HierarchicalLayer::new(2).with_writer(|| &WRITER));
    // This has to be its own integration test because we can't just set a
    // global default like this otherwise and not expect everything else to
    // break.
    set_global_default(subscriber).unwrap();

    tracing::error!("We can never expect the unexpected.");

    let output = WRITER.0.lock().unwrap();
    let output = str::from_utf8(&output).unwrap();

    // If this test finished we're happy. Let's just also check that we did
    // in fact log _something_ and that the logs from within the writer did
    // not actually go through.
    assert!(output.contains("We can never expect the unexpected."));
    assert!(!output.contains("Nobody expects the Spanish Inquisition"));
}