/
panic_hook.rs
55 lines (50 loc) · 2.21 KB
/
panic_hook.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//! This example demonstrates how `tracing` events can be recorded from within a
//! panic hook, capturing the span context in which the program panicked.
//!
//! A custom panic hook can also be used to record panics that are captured
//! using `catch_unwind`, such as when Tokio catches panics in spawned async
//! tasks. See the `tokio_panic_hook.rs` example for an example of this.
fn main() {
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.finish();
// NOTE: Using `tracing` in a panic hook requires the use of the *global*
// trace dispatcher (`tracing::subscriber::set_global_default`), rather than
// the per-thread scoped dispatcher
// (`tracing::subscriber::with_default`/`set_default`). With the scoped trace
// dispatcher, the subscriber's thread-local context may already have been
// torn down by unwinding by the time the panic handler is reached.
tracing::subscriber::set_global_default(subscriber).unwrap();
// Set a panic hook that records the panic as a `tracing` event at the
// `ERROR` verbosity level.
//
// If we are currently in a span when the panic occurred, the logged event
// will include the current span, allowing the context in which the panic
// occurred to be recorded.
std::panic::set_hook(Box::new(|panic| {
// If the panic has a source location, record it as structured fields.
if let Some(location) = panic.location() {
// On nightly Rust, where the `PanicInfo` type also exposes a
// `message()` method returning just the message, we could record
// just the message instead of the entire `fmt::Display`
// implementation, avoiding the duplicated location
tracing::error!(
message = %panic,
panic.file = location.file(),
panic.line = location.line(),
panic.column = location.column(),
);
} else {
tracing::error!(message = %panic);
}
}));
for i in 0..10 {
check_number(i);
}
}
#[tracing::instrument]
fn check_number(x: i32) {
if x % 2 == 0 {
panic!("I don't work with even numbers!");
}
}