Skip to content

Commit 20f72a1

Browse files
authored
Merge pull request #393 from Shourya742/2026-03-30-add-panic-hook
Add panic hook to pass panic and backtrace as a tracing event
2 parents a0f2703 + 399dd45 commit 20f72a1

1 file changed

Lines changed: 19 additions & 9 deletions

File tree

stratum-apps/src/config_helpers/logging.rs

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use std::{
2+
backtrace::Backtrace,
23
fs::OpenOptions,
34
io::{self, IsTerminal},
5+
panic,
46
path::Path,
57
str::FromStr,
68
};
@@ -23,15 +25,13 @@ pub fn init_logging(log_file: Option<&Path>) {
2325
Some(path) => {
2426
// Log to both file and stdout
2527
let path = path.to_owned();
26-
let file_layer = fmt::layer()
27-
.with_writer(move || {
28-
OpenOptions::new()
29-
.create(true)
30-
.append(true)
31-
.open(&path)
32-
.expect("Failed to open log file")
33-
})
34-
.with_ansi(false);
28+
// Open file only once, and not on every write.
29+
let file = OpenOptions::new()
30+
.create(true)
31+
.append(true)
32+
.open(&path)
33+
.expect("Failed to open log file");
34+
let file_layer = fmt::layer().with_writer(file).with_ansi(false);
3535
Box::new(
3636
Registry::default()
3737
.with(env_filter)
@@ -46,4 +46,14 @@ pub fn init_logging(log_file: Option<&Path>) {
4646
};
4747

4848
tracing::subscriber::set_global_default(subscriber).expect("Failed to set global subscriber");
49+
50+
// Set up a panic hook that records panic information and a backtrace
51+
// as tracing events, ensuring they are persisted in the log file.
52+
let default_panic_hook = panic::take_hook();
53+
panic::set_hook(Box::new(move |panic_info| {
54+
let backtrace = Backtrace::force_capture();
55+
tracing::error!("panic: {panic_info}");
56+
tracing::error!("Backtrace: {backtrace}");
57+
default_panic_hook(panic_info);
58+
}));
4959
}

0 commit comments

Comments
 (0)