| 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 | pub fn install(path: PathBuf) { |
| 12 | let _ = PATH.set(path); |
| 13 | } |
| 14 | |
| 15 | pub fn record(message: impl AsRef<str>) { |
| 16 | let message = message.as_ref(); |
| 17 | eprintln!("{message}"); |
| 18 | let Some(path) = PATH.get() else { |
| 19 | return; |
| 20 | }; |
| 21 | let full = std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > MAX_BYTES); |
| 22 | let file = OpenOptions::new() |
| 23 | .create(true) |
| 24 | .write(true) |
| 25 | .append(!full) |
| 26 | .truncate(full) |
| 27 | .open(path); |
| 28 | if let Ok(mut file) = file { |
| 29 | let _ = writeln!(file, "{} {message}", line_prefix()); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn line_prefix() -> String { |
| 34 | format!( |
| 35 | "{} {}", |
| 36 | chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"), |
| 37 | env!("TEAMS_BUILD_VERSION") |
| 38 | ) |
| 39 | } |