Skip to content

panic hook to log async backtrace to stderr #43

@amunra

Description

@amunra

I came across this crate because I was looking for a way to debug a panic in my code in a tokio application.

I've annotated all my async functions and I wired up a custom panic handler.

My current hacky code is the following:

static ASYNC_PANIC_OCCURRED: AtomicBool = AtomicBool::new(false);

pub fn install_panic_hook() {
    let default_hook = panic::take_hook();
    panic::set_hook(Box::new(move |panic_info| {
        if tokio::runtime::Handle::try_current().is_ok() {
            if !ASYNC_PANIC_OCCURRED.swap(true, Ordering::SeqCst) {
                let bt = async_backtrace::backtrace();
                let mut bt_buffer = String::new();
                if let Some(bt) = bt {
                    let locations = &*bt;
                    for (index, loc) in locations.iter().enumerate() {
                        write!(bt_buffer, "{index:3}: {loc:?}\n").unwrap();
                    }
                } else {
                    bt_buffer.push_str("[no accessible async backtrace]");
                }
                let all = async_backtrace::taskdump_tree(true);
                eprintln!(
                    "=== Async Backtrace (panic occurred in tokio runtime) ===\n\
                    {bt_buffer}\n\
                    ------- TASK DUMP TREE -------\n\
                    {all}\n\
                    === End Async Backtrace ===\n"
                );
            }
        }

        default_hook(panic_info);
    }));
}

Granted that I should implement this differently not to allocate on panic and trap/supress any panics that may be raised within the handler itsef, but that's a different matter.

More fundamentally, I'm struggling to get let bt = async_backtrace::backtrace(); working: It's always returning None.

Side note: It doesn't get any better if I remove the atomic boolean guard. I suspect tokio is trapping/re-raising the panic a number of times? The boolean is a workaround hack for that.

I would appreciate some guidance.

Thank you!

P.S.: async_backtrace::taskdump_tree(true); does, at least, work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions