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 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 here !
stack backtrace:
   0: rust_begin_unwind
             at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962/library\std\src/
   1: core::panicking::panic_fmt
             at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962/library\core\src/
   2: panic_message::main
             at .\src\bin\
   3: core::ops::function::FnOnce::call_once
             at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962\library\core\src\ops/
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 !

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.