31

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ynimous
  • 4,642
  • 6
  • 27
  • 43

2 Answers2

42

Rust uses the backtrace crate to print the backtrace in case of panics (has been merged in PR #60852).

A simple example can be found in the crate documentation

use backtrace::Backtrace;

fn main() {
    let bt = Backtrace::new();

    // do_some_work();

    println!("{:?}", bt);
}

which gives for example

stack backtrace:
   0: playground::main::h6849180917e9510b (0x55baf1676201)
             at src/main.rs:4
   1: std::rt::lang_start::{{closure}}::hb3ceb20351fe39ee (0x55baf1675faf)
             at /rustc/3c235d5600393dfe6c36eeed34042efad8d4f26e/src/libstd/rt.rs:64
   2: {{closure}} (0x55baf16be492)
             at src/libstd/rt.rs:49
      do_call<closure,i32>
             at src/libstd/panicking.rs:293
   3: __rust_maybe_catch_panic (0x55baf16c00b9)
             at src/libpanic_unwind/lib.rs:87
   4: try<i32,closure> (0x55baf16bef9c)
             at src/libstd/panicking.rs:272
      catch_unwind<closure,i32>
             at src/libstd/panic.rs:388
      lang_start_internal
             at src/libstd/rt.rs:48
   5: std::rt::lang_start::h2c4217f9057b6ddb (0x55baf1675f88)
             at /rustc/3c235d5600393dfe6c36eeed34042efad8d4f26e/src/libstd/rt.rs:64
   6: main (0x55baf16762f9)
   7: __libc_start_main (0x7fab051b9b96)
   8: _start (0x55baf1675e59)
   9: <unknown> (0x0)
hellow
  • 12,430
  • 7
  • 56
  • 79
30

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

Mika Vatanen
  • 3,782
  • 1
  • 28
  • 33
  • 4
    @ynimous This is the correct answer these days, I think it would be worthwhile to change the correct answer checkmark :) – Stefnotch Mar 05 '23 at 08:07
  • is it possible to pop the current function from the backtrace? then we could build nice strings with callstacks in error structs – Benni May 27 '23 at 09:28