use core::fmt;
use std::error::Error;
struct PanicRecord {
message: String,
}
impl fmt::Debug for PanicRecord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Panic")
}
}
impl fmt::Display for PanicRecord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl Error for PanicRecord {}
pub(crate) fn install() {
std::panic::set_hook(Box::new(|info| {
let panic_text = if let Some(text) = info.payload().downcast_ref::<&str>() {
(*text).to_owned()
} else if let Some(text) = info.payload().downcast_ref::<String>() {
text.clone()
} else {
"Box<dyn Any>".to_owned()
};
let message = match info.location() {
Some(location) => format!(
"{panic_text} at {}:{}:{}",
location.file(),
location.line(),
location.column()
),
None => panic_text,
};
let stack = if backtrace_is_off() {
None
} else {
Some(std::backtrace::Backtrace::force_capture().to_string())
};
let thread = std::thread::current();
let thread_name = thread.name().unwrap_or("<unnamed>").to_owned();
let record = PanicRecord { message };
let error: &(dyn Error + 'static) = &record;
match stack {
Some(stack) => tracing::error!(
thread = thread_name.as_str(),
error = error,
exception_stack = stack.as_str(),
"panic"
),
None => tracing::error!(thread = thread_name.as_str(), error = error, "panic"),
}
}));
}
fn backtrace_is_off() -> bool {
matches!(std::env::var("RUST_BACKTRACE").as_deref(), Ok("0"))
}