How to print stack backtrace when I implement the panic hook

For the panic hook , it will pass in the PanicInfo only include location and panic message , but I also hope to get the stack backtrace

pub fn panic_handler(info: &PanicInfo) {
    println!("{}", info);
}

The code above will not print including stack backtrace

panicked at src\bin\panic_message.rs:5:5:
Panic here !
error: process didn't exit successfully: `target\debug\panic_message.exe` (exit code: 101)

But the std did

thread 'main' panicked at src\bin\panic_message.rs:5:5:
Panic here !
stack backtrace:
   0: rust_begin_unwind
             at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962/library\std\src/panicking.rs:597:5
   1: core::panicking::panic_fmt
             at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962/library\core\src/panicking.rs:72:14
   2: panic_message::main
             at .\src\bin\panic_message.rs:5:5
   3: core::ops::function::FnOnce::call_once
             at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962\library\core\src\ops/function.rs:250:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a 
verbose backtrace.
error: process didn't exit successfully: `target\debug\panic_message.exe` (exit code: 101)

The panic hook itself has to capture the backtrace. When the panic hook runs the entire stack is still intact. Depending on your needs you may be able to run the original panic hook after doing whatever you want to do in the panic hook by doing std::panic::take_hook() before setting the new panic hook and passing the original hook to your custom hook. Or you can use std::backtrace::Backtrace::capture() and then print the returned value/

1 Like

Thanks , it did work !