p2p_testing/
log.rs

1use std::{env, sync::atomic::AtomicBool};
2
3use openmina_core::log::inner::Level;
4use tracing::Subscriber;
5use tracing_subscriber::{layer::SubscriberExt, Layer};
6
7lazy_static::lazy_static! {
8    pub(crate) static ref LOG: () = initialize_logging();
9
10    pub(crate) static ref ERROR: AtomicBool = Default::default();
11}
12
13/// Tracing subscriber that panics on `Error` level events.
14struct ErrorPanicLayer;
15
16impl<S> Layer<S> for ErrorPanicLayer
17where
18    S: Subscriber,
19{
20    fn on_event(
21        &self,
22        event: &tracing::Event<'_>,
23        _ctx: tracing_subscriber::layer::Context<'_, S>,
24    ) {
25        if event.metadata().level() == &Level::ERROR {
26            ERROR.store(true, std::sync::atomic::Ordering::Relaxed);
27        }
28    }
29}
30
31fn initialize_logging() {
32    let level = std::env::var("OPENMINA_TRACING_LEVEL")
33        .ok()
34        .and_then(|level| match level.parse() {
35            Ok(v) => Some(v),
36            Err(e) => {
37                eprintln!("cannot parse {level} as tracing level: {e}");
38                None
39            }
40        })
41        .unwrap_or(Level::INFO);
42    let builder = tracing_subscriber::FmtSubscriber::builder()
43        .with_max_level(level)
44        .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stdout()))
45        .with_test_writer()
46        //.with_timer(ReduxTimer)
47        ;
48    let error_panic_layer = env::var("PANIC_ON_TRACING_ERROR")
49        .ok()
50        .and_then(|var| var.parse::<bool>().ok())
51        .unwrap_or(true)
52        .then_some(ErrorPanicLayer);
53    let subscriber = builder.finish().with(error_panic_layer);
54    tracing::subscriber::set_global_default(subscriber)
55        .expect("global subscriber should be configurable");
56
57    if env::var("OPENMINA_LOG_TRACER")
58        .ok()
59        .and_then(|var| var.parse::<bool>().ok())
60        .unwrap_or_default()
61    {
62        if let Err(err) = tracing_log::LogTracer::init() {
63            eprintln!("cannot initialize log tracing bridge: {err}");
64        }
65    }
66}