Search code examples
rustbacktrace

Is it possible to print a backtrace in Rust without panicking?


Is it possible to print a backtrace (assuming RUST_BACKTRACE is enabled) without panicking? It seems that the only way of doing that is calling via panic!. If not, is there a reason for it?


Solution

  • You can use std::backtrace::Backtrace since rust 1.65.0:

    use std::backtrace::Backtrace;
    
    fn main() {
        // Print backtrace if either RUST_BACKTRACE or RUST_LIB_BACKTRACE is set
        println!("Custom backtrace: {}", Backtrace::capture());
    
        // or forcibly capture the backtrace regardless of environment variable configuration
        println!("Custom backtrace: {}", Backtrace::force_capture());
    }
    

    Documentation: https://doc.rust-lang.org/std/backtrace/struct.Backtrace.html