From a59bbacb297191e6dce4efe7032382da77c9e04d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sun, 15 Aug 2021 06:34:07 -0700 Subject: [PATCH] feat(tracing): use hook to log errors on panics The two bugs raised in issues #1 and #2 were due to panics that were not visible in the logs, which left the process hanging and unresponsive, ultimately needing to be force killed with a command like 'Stop-Process -Name komorebi'. The only way to even verify that a panic had taken place and what the panic related to, was to run '$env:RUST_BACKTRACE ='full'; komorebi.exe', wait for the panic, then restore the now-hidden window with 'komorebic restore-windows' to finally see the panic message. This commit integrates an example from the 'tracing' repo, which through the addition of a panic hook, logs out panics as errors. Hopefully this will debugging much easier in the future. re #1, re #2 --- komorebi/src/main.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index d188c205..bd2e25a9 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -82,6 +82,31 @@ fn setup() -> Result { ), )?; + // https://github.com/tokio-rs/tracing/blob/master/examples/examples/panic_hook.rs + // Set a panic hook that records the panic as a `tracing` event at the + // `ERROR` verbosity level. + // + // If we are currently in a span when the panic occurred, the logged event + // will include the current span, allowing the context in which the panic + // occurred to be recorded. + std::panic::set_hook(Box::new(|panic| { + // If the panic has a source location, record it as structured fields. + if let Some(location) = panic.location() { + // On nightly Rust, where the `PanicInfo` type also exposes a + // `message()` method returning just the message, we could record + // just the message instead of the entire `fmt::Display` + // implementation, avoiding the duplciated location + tracing::error!( + message = %panic, + panic.file = location.file(), + panic.line = location.line(), + panic.column = location.column(), + ); + } else { + tracing::error!(message = %panic); + } + })); + Ok(guard) }