pub use chatdbg_macros::main;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::panic;
use std::sync::{
atomic::{AtomicBool, Ordering},
Mutex,
};
use std::thread;
lazy_static::lazy_static! {
static ref FILE_MUTEX: Mutex<()> = Mutex::new(());
static ref FILE_CREATED: AtomicBool = AtomicBool::new(false);
}
pub fn chatdbg() {
panic::set_hook(Box::new(|info| {
let _guard = FILE_MUTEX.lock().unwrap(); let payload = if let Some(s) = info.payload().downcast_ref::<&str>() {
*s
} else {
"Box<Any>"
};
let location = if let Some(location) = info.location() {
format!(" at '{}' line {}", location.file(), location.line())
} else {
String::from("")
};
let message = format!(
"thread '{}' panicked with '{}'{}",
thread::current().name().unwrap_or("<unnamed>"),
payload,
location
);
eprintln!("{}", message);
let filename = "panic_log.txt";
let mut file = if FILE_CREATED.swap(true, Ordering::SeqCst) {
OpenOptions::new()
.create(true)
.append(true)
.open(filename)
.expect("Unable to open file")
} else {
File::create(filename).expect("Unable to create file")
};
writeln!(file, "{}", message).expect("Unable to write to file");
}));
}