|
| 1 | +//! Panic hook implementation for tracking panics. |
| 2 | +
|
| 3 | +#[cfg(feature = "metrics")] |
| 4 | +use crate::alerts::_private::DefaultRegistry; |
| 5 | + |
| 6 | +use super::_private::{DefaultBuilderState, HasRegistry, NeedsRegistry}; |
| 7 | +use super::{FatalErrorRegistry, HOOK_INSTALLED}; |
| 8 | +use std::panic::{self, PanicHookInfo}; |
| 9 | + |
| 10 | +/// Returns a builder for configuring and installing the panic hook. |
| 11 | +/// |
| 12 | +/// When the `metrics` feature is enabled, a default registry is provided and |
| 13 | +/// `.init()` can be called immediately. When `metrics` is disabled, you must |
| 14 | +/// call `.with_registry()` before `.init()`. |
| 15 | +/// |
| 16 | +/// See the module-level docs for more information: [`crate::alerts`] |
| 17 | +pub fn panic_hook() -> PanicHookBuilder<DefaultBuilderState> { |
| 18 | + PanicHookBuilder { |
| 19 | + state: Default::default(), |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +/// Builder for configuring the panic hook. |
| 24 | +/// |
| 25 | +/// This builder uses the typestate pattern to ensure at compile time that a |
| 26 | +/// registry is available before [`PanicHookBuilder::init()`] can be called. |
| 27 | +/// When the `metrics` feature is enabled, `foundations::metrics` is used. |
| 28 | +#[must_use = "A PanicHookBuilder should be installed with .init()"] |
| 29 | +pub struct PanicHookBuilder<State> { |
| 30 | + pub(super) state: State, |
| 31 | +} |
| 32 | + |
| 33 | +impl PanicHookBuilder<NeedsRegistry> { |
| 34 | + /// Provide a custom metrics registry for recording fatal error metrics. |
| 35 | + /// |
| 36 | + /// This is required when the `metrics` feature is disabled. |
| 37 | + pub fn with_registry<R>(self, registry: R) -> PanicHookBuilder<HasRegistry<R>> |
| 38 | + where |
| 39 | + R: FatalErrorRegistry + 'static, |
| 40 | + { |
| 41 | + PanicHookBuilder { |
| 42 | + state: HasRegistry { registry }, |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +/// When `metrics` feature is enabled, allow overriding the default registry. |
| 48 | +#[cfg(feature = "metrics")] |
| 49 | +impl PanicHookBuilder<HasRegistry<DefaultRegistry>> { |
| 50 | + /// Provide a custom metrics registry for recording fatal error metrics. |
| 51 | + /// |
| 52 | + /// This overrides the default foundations metrics registry. |
| 53 | + pub fn with_registry<R>(self, registry: R) -> PanicHookBuilder<HasRegistry<R>> |
| 54 | + where |
| 55 | + R: FatalErrorRegistry + 'static, |
| 56 | + { |
| 57 | + PanicHookBuilder { |
| 58 | + state: HasRegistry { registry }, |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +impl<R: FatalErrorRegistry + 'static> PanicHookBuilder<HasRegistry<R>> { |
| 64 | + /// Install the panic hook. |
| 65 | + /// |
| 66 | + /// Returns `true` if this is the first installation, `false` if the hook |
| 67 | + /// was already installed (subsequent calls are no-ops). |
| 68 | + pub fn init(self) -> bool { |
| 69 | + let first_install = HOOK_INSTALLED.set(()).is_ok(); |
| 70 | + if !first_install { |
| 71 | + return false; |
| 72 | + } |
| 73 | + |
| 74 | + let registry = self.state.registry; |
| 75 | + let previous = panic::take_hook(); |
| 76 | + |
| 77 | + panic::set_hook(Box::new(move |panic_info| { |
| 78 | + registry.inc_panics_total(1); |
| 79 | + |
| 80 | + log_panic(panic_info); |
| 81 | + previous(panic_info); |
| 82 | + })); |
| 83 | + |
| 84 | + true |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +/// Log the panic using foundations telemetry if initialized, otherwise print JSON to stderr. |
| 89 | +fn log_panic(panic_info: &PanicHookInfo<'_>) { |
| 90 | + let location = panic_info.location(); |
| 91 | + let payload = panic_payload_as_str(panic_info); |
| 92 | + |
| 93 | + // Use foundations logging if telemetry is initialized |
| 94 | + #[cfg(feature = "logging")] |
| 95 | + if crate::telemetry::is_initialized() { |
| 96 | + crate::telemetry::log::error!( |
| 97 | + "panic occurred"; |
| 98 | + "payload" => payload, |
| 99 | + "location" => ?location, |
| 100 | + ); |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + // Fallback to printing structured JSON to stderr |
| 105 | + let location_str = location |
| 106 | + .map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column())) |
| 107 | + .unwrap_or_else(|| "<unknown>".to_string()); |
| 108 | + |
| 109 | + eprintln!( |
| 110 | + r#"{{"level":"error","msg":"panic occurred","payload":"{}","location":"{}"}}"#, |
| 111 | + payload.replace('\\', "\\\\").replace('"', "\\\""), |
| 112 | + location_str |
| 113 | + ); |
| 114 | +} |
| 115 | + |
| 116 | +fn panic_payload_as_str<'a>(panic_info: &'a PanicHookInfo<'_>) -> &'a str { |
| 117 | + let payload = panic_info.payload(); |
| 118 | + |
| 119 | + if let Some(s) = payload.downcast_ref::<&str>() { |
| 120 | + s |
| 121 | + } else if let Some(s) = payload.downcast_ref::<String>() { |
| 122 | + s.as_str() |
| 123 | + } else { |
| 124 | + "<non-string panic payload>" |
| 125 | + } |
| 126 | +} |
0 commit comments