|
| 1 | +use std::io::IsTerminal; |
| 2 | +use std::path::PathBuf; |
| 3 | +use std::time::SystemTime; |
| 4 | +use std::{env, fs, io}; |
| 5 | + |
| 6 | +use tracing_chrome::ChromeLayerBuilder; |
| 7 | +use tracing_subscriber::filter::{EnvFilter, LevelFilter, Targets}; |
| 8 | +use tracing_subscriber::fmt::Layer; |
| 9 | +use tracing_subscriber::fmt::time::Uptime; |
| 10 | +use tracing_subscriber::prelude::*; |
| 11 | + |
| 12 | +pub fn init_logging() -> Option<impl Drop> { |
| 13 | + let mut guard = None; |
| 14 | + |
| 15 | + let fmt_layer = Layer::new() |
| 16 | + .with_writer(io::stderr) |
| 17 | + .with_ansi(io::stderr().is_terminal()) |
| 18 | + .with_timer(Uptime::default()) |
| 19 | + .with_filter( |
| 20 | + EnvFilter::builder() |
| 21 | + .with_default_directive(LevelFilter::WARN.into()) |
| 22 | + .with_env_var("CAIRO_DEBUGGER_LOG") |
| 23 | + .from_env_lossy(), |
| 24 | + ); |
| 25 | + |
| 26 | + let tracing_profile = env::var("CAIRO_DEBUGGER_TRACING_PROFILE").ok().is_some_and(|var| { |
| 27 | + let s = var.as_str(); |
| 28 | + s == "true" || s == "1" |
| 29 | + }); |
| 30 | + |
| 31 | + let profile_layer = if tracing_profile { |
| 32 | + let mut path = PathBuf::from(format!( |
| 33 | + "./cairo-debugger-profile-{}.json", |
| 34 | + SystemTime::UNIX_EPOCH.elapsed().unwrap().as_micros() |
| 35 | + )); |
| 36 | + |
| 37 | + // Create the file now, so that we early panic, and `fs::canonicalize` will work. |
| 38 | + let profile_file = fs::File::create(&path).expect("failed to create profile file"); |
| 39 | + |
| 40 | + // Try to canonicalize the path so that it is easier to find the file from logs. |
| 41 | + if let Ok(canonical) = fs::canonicalize(&path) { |
| 42 | + path = canonical; |
| 43 | + } |
| 44 | + |
| 45 | + eprintln!("Cairo Debugger run will output tracing profile to: {}", path.display()); |
| 46 | + eprintln!( |
| 47 | + "Open that file with https://ui.perfetto.dev (or chrome://tracing) to analyze it" |
| 48 | + ); |
| 49 | + |
| 50 | + let (profile_layer, profile_layer_guard) = |
| 51 | + ChromeLayerBuilder::new().writer(profile_file).include_args(true).build(); |
| 52 | + |
| 53 | + // Filter out less important logs because they're too verbose, |
| 54 | + // and with them the profile file quickly grows to several GBs of data. |
| 55 | + let profile_layer = profile_layer.with_filter( |
| 56 | + Targets::new().with_default(LevelFilter::TRACE).with_target("salsa", LevelFilter::WARN), |
| 57 | + ); |
| 58 | + |
| 59 | + guard = Some(profile_layer_guard); |
| 60 | + Some(profile_layer) |
| 61 | + } else { |
| 62 | + None |
| 63 | + }; |
| 64 | + |
| 65 | + tracing::subscriber::set_global_default( |
| 66 | + tracing_subscriber::registry().with(fmt_layer).with(profile_layer), |
| 67 | + ) |
| 68 | + .expect("could not set up global logger"); |
| 69 | + |
| 70 | + guard |
| 71 | +} |
0 commit comments