In Rust, what does std::panic::set_hook let a service do, when does the hook run, and how do you keep the default output?
answer
- one global hook, every thread
- before unwinding or abort
- take_hook hands back the old one
- PanicHookInfo: location and payload
basics
~20 sset_hook replaces the single process-wide function std calls on every panic, on the panicking thread, before unwinding or aborting. Services use it to log panics their own way; calling take_hook first and forwarding to it keeps the default message.
solid answer
~40 s`std::panic::set_hook` takes a `Box<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static>` and installs it as the one global panic hook, replacing the previous one. std calls it on the panicking thread after the panic starts and before the runtime unwinds or aborts, so it runs under both strategies and even for panics that `catch_unwind` later catches. `PanicHookInfo` offers `location()` and `payload()`, and since Rust 1.91 `payload_as_str()`. A service hook typically writes one structured log line with the thread name, location and message. To keep std's usual stderr output and its `RUST_BACKTRACE` handling, call `take_hook()` first (it returns the current hook and reinstalls the default) and call that from your closure. The hook observes a panic; it cannot cancel it.
code
rust · 27 linesuse std::panic;
fn main() {
let default_hook = panic::take_hook();
panic::set_hook(Box::new(move |info| {
let location = info
.location()
.map(|l| format!("{}:{}", l.file(), l.line()))
.unwrap_or_default();
let msg = info.payload_as_str().unwrap_or("<non-string payload>");
let thread = std::thread::current();
eprintln!(
"{{\"event\":\"panic\",\"thread\":\"{}\",\"at\":\"{location}\",\"msg\":\"{msg}\"}}",
thread.name().unwrap_or("<unnamed>")
);
default_hook(info); // keep the standard message and RUST_BACKTRACE behaviour
}));
let id = std::env::args().count() + 41;
let worker = std::thread::Builder::new()
.name("worker-1".into())
.spawn(move || panic!("order {id} has no line items"))
.unwrap();
let joined = worker.join();
println!("join returned Err: {}", joined.is_err());
println!("payload is String: {}", joined.unwrap_err().is::<String>());
}go deeper
Know that a panic prints its message through a replaceable hook, and that std::panic::set_hook is how a program changes what gets printed.
Explain that the hook is global, runs on the panicking thread before unwinding or abort, and how take_hook lets you chain to the default output.
Show a production hook: structured log line, thread name and location, a forced backtrace, chained default output, and no unwrap or locks that could abort the process.
Decide who owns the hook in a multi-crate codebase: the binary installs it once at startup, and libraries never call set_hook behind the application's back.
## What the panic hook is When a Rust thread panics, std calls a **panic hook**: a function that reports the panic. A default hook is registered at startup; it prints the thread name, the source location and the message to standard error, and prints a backtrace when `RUST_BACKTRACE` asks for one. `std::panic::set_hook` replaces it: `pub fn set_hook(hook: Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>)` The hook is a **global resource**: there is exactly one for the whole process, shared by every thread, and the last `set_hook` call wins. The `Sync + Send + 'static` bounds follow from that, since any thread may call it at any time. ## When it runs The order is fixed: 1. Something panics: `panic!`, a failed `unwrap`, an out-of-bounds index. 2. std calls the hook **on the panicking thread**, so `std::thread::current()` inside the hook names the thread that failed. 3. Only then does the panic runtime take over and either unwind or abort. Consequences worth knowing: - The hook runs under **both** the unwind and the abort strategy, which makes it the one reliable place to log a panic in an abort build. - It runs even when a `catch_unwind` further up will catch the panic, so a caught panic still prints unless you replace the hook. - `std::panic::resume_unwind`, used to re-raise a payload that was already caught, deliberately does **not** call the hook. - The hook cannot stop the panic. When it returns, unwinding or aborting continues. ## What PanicHookInfo carries | Item | Gives you | Stable since | |---|---|---| | `location()` | `Option<&'static Location<'static>>`: file, line, column (always `Some` today) | 1.10 | | `payload()` | `&(dyn Any + Send)`, the raw payload to downcast | 1.10 | | `payload_as_str()` | `Option<&str>` for a `&'static str` or `String` payload | 1.91 | | `Display` impl | `panicked at file:line:col:` followed by the message | 1.26 | The type was called `PanicInfo` until Rust 1.81 renamed it `PanicHookInfo`; the old name remains as a deprecated alias. `core::panic::PanicInfo` is a different type, the argument of the `#[panic_handler]` used in no_std programs. ## Chaining to the default hook Replacing the hook outright drops std's familiar output. The usual pattern keeps it: - call `std::panic::take_hook()`, which **unregisters the current hook, returns it, and reinstalls the default**; - move the returned box into your closure; - do your own work (a JSON log line, a metrics counter, a crash-report file), then call the saved hook with the same `&PanicHookInfo`. The saved default hook still honours `RUST_BACKTRACE` and still prints the backtrace hint. If a hook needs a backtrace regardless of environment variables, `std::backtrace::Backtrace::force_capture()` captures one; `Backtrace::capture()` respects `RUST_BACKTRACE` and `RUST_LIB_BACKTRACE`. ## Rules and traps - **Do not panic in the hook.** A panic raised while the hook is running makes std print `thread panicked while processing panic. aborting.` and abort the process. - **Install it early, from one place.** Because it is global, the binary should set it once at startup. A library that calls `set_hook` overrides the application's choice. - `set_hook` and `take_hook` **panic if called from a panicking thread**, for example from a `Drop` impl running during unwinding. - Keep the hook simple. It runs in a thread that is already in trouble; taking a lock that the panicking code may itself hold can deadlock or panic. - A second panic on a thread that is already unwinding makes the default hook print a full backtrace, whatever `RUST_BACKTRACE` says. ## What a service hook should do A production hook is small and boring on purpose: - write **one structured line** per panic with the thread name (`std::thread::current().name()`), the location and the message from `payload_as_str()`, falling back to a placeholder for a payload that is neither `&str` nor `String`; - optionally attach a forced backtrace and bump a panic counter that monitoring alerts on; - forward to the saved default hook so local runs still look normal. Under the abort strategy this line is the only record of where and why the process died, because no destructor and no `join` will run afterwards; under unwind it is the record that survives even when a `catch_unwind` swallows the panic. Either way the hook observes; isolating the failure is the job of thread boundaries, `catch_unwind` and the panic strategy.
- Does a Rust panic hook run for a panic that `catch_unwind` later catches?Yes. std calls the hook before unwinding starts, so it fires even though a `catch_unwind` frame will stop the unwind; that is why a caught panic still prints a message. Re-raising a caught payload with `std::panic::resume_unwind` is the case that skips the hook.
- What happens if a Rust panic hook itself panics?std treats a panic inside the hook as unrecoverable: it prints `thread panicked while processing panic. aborting.` and aborts the process, even under the unwind strategy and even inside `catch_unwind`. Keep hooks free of `unwrap`, indexing and locks.
- How can a Rust panic hook log a backtrace even when RUST_BACKTRACE is not set?Call `std::backtrace::Backtrace::force_capture()` inside the hook; it ignores `RUST_BACKTRACE` and `RUST_LIB_BACKTRACE` and always captures. `Backtrace::capture()` is a no-op unless one of those variables enables it. Capturing is expensive, which is acceptable on a path that only runs when something has already gone wrong.
- Each thread can install its own panic hook.
- The hook can stop the panic and let the thread carry on.
- set_hook adds a hook alongside the default, so both run.
- Under panic = abort the panic hook is skipped.
- The hook only sees panics that catch_unwind does not catch.
Assumes Rust 1.99; PanicHookInfo replaced the PanicInfo name in 1.81, and PanicHookInfo::payload_as_str is stable since 1.91.