Skip to main content

stylex_logs/
initializer.rs

1use env_logger::{Builder, WriteStyle};
2use log::LevelFilter;
3use std::{panic, sync::Once};
4use stylex_macros::stylex_error::is_panic_stderr_suppressed;
5
6use crate::constants::STYLEX_PREFIX;
7
8use super::formatter::log_formatter;
9
10static INIT: Once = Once::new();
11
12pub fn initialize() {
13  INIT.call_once(|| {
14    Builder::new()
15      .format(log_formatter)
16      .filter_level(LevelFilter::Warn)
17      .parse_env("STYLEX_DEBUG") // Allow override via environment variable
18      .write_style(WriteStyle::Always)
19      .init();
20
21    panic::set_hook(Box::new(|info| {
22      if is_panic_stderr_suppressed() {
23        return;
24      }
25
26      let msg = if let Some(s) = info.payload().downcast_ref::<String>() {
27        s.clone()
28      } else if let Some(s) = info.payload().downcast_ref::<&str>() {
29        s.to_string()
30      } else {
31        format!("{} Unknown internal error", STYLEX_PREFIX).to_string()
32      };
33
34      // StyleX panics already carry the branded prefix in their Display output;
35      // print them as-is.  For any other (unexpected) panic, wrap with the prefix.
36      if msg.contains(STYLEX_PREFIX) {
37        eprintln!("{}", msg);
38      } else {
39        eprintln!("{} {}", STYLEX_PREFIX, msg);
40      }
41    }));
42  });
43}