| 1 | use std::backtrace::Backtrace; |
| 2 | use std::fs::OpenOptions; |
| 3 | use std::io::Write; |
| 4 | use std::panic::PanicHookInfo; |
| 5 | use std::path::PathBuf; |
| 6 | |
| 7 | pub const CRASH_LOG_FILE: &str = "crash.log"; |
| 8 | |
| 9 | pub fn install(path: PathBuf) { |
| 10 | let previous = std::panic::take_hook(); |
| 11 | std::panic::set_hook(Box::new(move |info| { |
| 12 | if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&path) { |
| 13 | let _ = file.write_all(entry(info, &Backtrace::force_capture().to_string()).as_bytes()); |
| 14 | } |
| 15 | previous(info); |
| 16 | })); |
| 17 | } |
| 18 | |
| 19 | fn entry(info: &PanicHookInfo<'_>, backtrace: &str) -> String { |
| 20 | let location = info |
| 21 | .location() |
| 22 | .map(|location| format!("{}:{}:{}", location.file(), location.line(), location.column())) |
| 23 | .unwrap_or_default(); |
| 24 | let thread = std::thread::current(); |
| 25 | format!( |
| 26 | "=== {} build {} thread {}\npanic at {location}: {}\n{backtrace}\n", |
| 27 | chrono::Utc::now().to_rfc3339(), |
| 28 | env!("TEAMS_BUILD_VERSION"), |
| 29 | thread.name().unwrap_or("unnamed"), |
| 30 | message(info), |
| 31 | ) |
| 32 | } |
| 33 | |
| 34 | fn message(info: &PanicHookInfo<'_>) -> String { |
| 35 | let payload = info.payload(); |
| 36 | payload |
| 37 | .downcast_ref::<&str>() |
| 38 | .map(|text| (*text).to_owned()) |
| 39 | .or_else(|| payload.downcast_ref::<String>().cloned()) |
| 40 | .unwrap_or_else(|| "non-text panic payload".to_owned()) |
| 41 | } |