| 1 | use std::fs::OpenOptions; |
| 2 | use std::io::Write; |
| 3 | use std::path::PathBuf; |
| 4 | use std::sync::OnceLock; |
| 5 | |
| 6 | pub const DIAGNOSTICS_FILE: &str = "diagnostics.log"; |
| 7 | const MAX_BYTES: u64 = 1024 * 1024; |
| 8 | |
| 9 | static PATH: OnceLock<PathBuf> = OnceLock::new(); |
| 10 | |
| 11 | const WEBRTC_AUDIO_MARKERS: [&str; 3] = ["AdmProxy", "audio_device_core_win", "core_audio"]; |
| 12 | |
| 13 | pub fn install(path: PathBuf) { |
| 14 | let _ = PATH.set(path); |
| 15 | if log::set_logger(&WebrtcAudioLog).is_ok() { |
| 16 | log::set_max_level(log::LevelFilter::Debug); |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | struct WebrtcAudioLog; |
| 21 | |
| 22 | impl log::Log for WebrtcAudioLog { |
| 23 | fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { |
| 24 | metadata.target() == "libwebrtc" |
| 25 | } |
| 26 | |
| 27 | fn log(&self, entry: &log::Record<'_>) { |
| 28 | if !self.enabled(entry.metadata()) { |
| 29 | return; |
| 30 | } |
| 31 | let text = entry.args().to_string(); |
| 32 | if WEBRTC_AUDIO_MARKERS.iter().any(|marker| text.contains(marker)) { |
| 33 | record(format!("webrtc: {text}")); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | fn flush(&self) {} |
| 38 | } |
| 39 | |
| 40 | pub fn directory() -> Option<PathBuf> { |
| 41 | PATH.get().and_then(|path| path.parent()).map(PathBuf::from) |
| 42 | } |
| 43 | |
| 44 | pub fn record(message: impl AsRef<str>) { |
| 45 | let message = message.as_ref(); |
| 46 | eprintln!("{message}"); |
| 47 | let Some(path) = PATH.get() else { |
| 48 | return; |
| 49 | }; |
| 50 | let full = std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > MAX_BYTES); |
| 51 | let file = OpenOptions::new() |
| 52 | .create(true) |
| 53 | .write(true) |
| 54 | .append(!full) |
| 55 | .truncate(full) |
| 56 | .open(path); |
| 57 | if let Ok(mut file) = file { |
| 58 | let _ = writeln!(file, "{} {message}", line_prefix()); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | fn line_prefix() -> String { |
| 63 | format!( |
| 64 | "{} {}", |
| 65 | chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"), |
| 66 | env!("TEAMS_BUILD_VERSION") |
| 67 | ) |
| 68 | } |