Function tracing_panic::panic_hook

source ·
pub fn panic_hook(panic_info: &PanicInfo<'_>)
Expand description

A panic hook that emits an error-level tracing event when a panic occurs.

The default panic hook prints the panic information to stderr, which might or might not be picked up by your telemetry system.

This hook, instead, makes sure that panic information goes through the tracing pipeline you’ve configured.

§Usage

use tracing_panic::panic_hook;

fn main() {
    // Initialize your `tracing` subscriber however you like.
    // [...]
    // Then set the panic hook.
    // This should be done only once, at the beginning of your program.
    std::panic::set_hook(Box::new(panic_hook));
}

§Backtrace

If the capture-backtrace feature flag is enabled, tracing-panic will try to capture a backtrace.
Whether a backtrace is actually captured depends on the value of a few environment variables, defined in Rust’s standard library. Check out std’s documentation for more details.

§Preserving previous hook

Sometimes it’s desirable to preserve the previous panic hook, because other crates might rely on their panic hook integration to function properly.

For this behavior, you can do the following:

use tracing_panic::panic_hook;

fn main() {
    let prev_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        panic_hook(panic_info);
        prev_hook(panic_info);
    }));
}