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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
//! This crate provides `.unwrap_or_log()` and `.expect_or_log()` methods on `Result` and `Option` types that log failed unwraps to a [`tracing::Subscriber`]. This is useful when, for example, you are logging to syslog or a database, and you want your unwrap failures to show up there instead of being printed to `stderr`.
//!
//! Its API aims to mirror Rust's `std` — see all the [supported methods](#methods) below. Failed unwraps are logged at a level of [`ERROR`].
//!
//! [](https://crates.io/crates/tracing-unwrap)
//! [](https://docs.rs/tracing-unwrap)
//! [](https://github.com/abreis/tracing-unwrap)
//!
//! ### Usage
//! Add the following to your `Cargo.toml`:
//! ```toml
//! tracing-unwrap = "0.10"
//! ```
//!
//! Next, bring the [`ResultExt`] and/or [`OptionExt`] traits into scope, and make use of the new logging methods.
//! ```ignore
//! use tracing_unwrap::ResultExt;
//!
//! tracing_subscriber::fmt().init();
//! let not_great: Result<(), _> = Result::Err("not terrible");
//!
//! // Logs the failed unwrap and panics
//! not_great.unwrap_or_log();
//! ```
//!
//! ### Methods
//! | `std` method | `tracing-unwrap` form | trait |
//! |--------------------------------| ----------------------------------------|---------------|
//! | [`Result::unwrap()`] | [`Result::unwrap_or_log()`] | [`ResultExt`] |
//! | [`Result::expect(msg)`] | [`Result::expect_or_log(msg)`] | [`ResultExt`] |
//! | [`Result::unwrap_err()`] | [`Result::unwrap_err_or_log()`] | [`ResultExt`] |
//! | [`Result::expect_err(msg)`] | [`Result::expect_err_or_log(msg)`] | [`ResultExt`] |
//! | [`Option::unwrap()`] | [`Option::unwrap_or_log()`] | [`OptionExt`] |
//! | [`Option::expect(msg)`] | [`Option::expect_or_log(msg)`] | [`OptionExt`] |
//! | [`Option::unwrap_none()`]<sup>†</sup> | [`Option::unwrap_none_or_log()`] | [`OptionExt`] |
//! | [`Option::expect_none(msg)`]<sup>†</sup> | [`Option::expect_none_or_log(msg)`] | [`OptionExt`] |
//!
//! *†: no longer in `std`, see [`rust-lang/rust#62633`](https://github.com/rust-lang/rust/issues/62633)*<br/>
//!
//!
//! ### Features
//! * **`panic-quiet`**: causes failed unwraps to panic with an empty message.<br/>
//! This feature is enabled by default — if you'd like the unwrap error message to also show in the panic message, disable default features in your `Cargo.toml` as follows:<br/>
//! `tracing-unwrap = { version = "0.10", default-features = false }`
//!
//! * **`log-location`**: calls [`std::panic::Location::caller()`] to determine the location of a failed unwrap.
//!
//! [`tracing::Subscriber`]: https://docs.rs/tracing/*/tracing/trait.Subscriber.html
//! [`ResultExt`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.ResultExt.html
//! [`OptionExt`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.OptionExt.html
//! [`ERROR`]: https://docs.rs/tracing/*/tracing/struct.Level.html#associatedconstant.ERROR
//! [`Result::unwrap()`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap
//! [`Result::expect(msg)`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.expect
//! [`Result::unwrap_err()`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap_err
//! [`Result::expect_err(msg)`]: https://doc.rust-lang.org/std/result/enum.Result.html#method.expect_err
//! [`Option::unwrap()`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap
//! [`Option::expect(msg)`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.expect
//! [`Option::unwrap_none()`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap_none
//! [`Option::expect_none(msg)`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.expect_none
//! [`Result::unwrap_or_log()`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.ResultExt.html#tymethod.unwrap_or_log
//! [`Result::expect_or_log(msg)`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.ResultExt.html#tymethod.expect_or_log
//! [`Result::unwrap_err_or_log()`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.ResultExt.html#tymethod.unwrap_err_or_log
//! [`Result::expect_err_or_log(msg)`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.ResultExt.html#tymethod.expect_err_or_log
//! [`Option::unwrap_or_log()`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.OptionExt.html#tymethod.unwrap_or_log
//! [`Option::expect_or_log(msg)`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.OptionExt.html#tymethod.expect_or_log
//! [`Option::unwrap_none_or_log()`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.OptionExt.html#tymethod.unwrap_none_or_log
//! [`Option::expect_none_or_log(msg)`]: https://docs.rs/tracing-unwrap/*/tracing_unwrap/trait.OptionExt.html#tymethod.expect_none_or_log
//! [`std::panic::Location::caller()`]: https://doc.rust-lang.org/std/panic/struct.Location.html#method.caller
use std::fmt;
//
// Extension trait for Result types.
//
/// Extension trait for Result types.
pub trait ResultExt<T, E> {
/// Unwraps a result, yielding the content of an [`Ok`].
///
/// # Panics
///
/// Panics if the value is an [`Err`], logging a message provided by the
/// [`Err`]'s value to a [`tracing::Subscriber`] at an [`ERROR`] level.
///
/// [`ERROR`]: /tracing/0.1/tracing/struct.Level.html#associatedconstant.ERROR
fn unwrap_or_log(self) -> T
where
E: fmt::Debug;
/// Unwraps a result, yielding the content of an [`Ok`].
///
/// # Panics
///
/// Panics if the value is an [`Err`], logging the passed message and the
/// content of the [`Err`] to a [`tracing::Subscriber`] at an [`ERROR`] level.
///
/// [`ERROR`]: /tracing/0.1/tracing/struct.Level.html#associatedconstant.ERROR
fn expect_or_log(self, msg: &str) -> T
where
E: fmt::Debug;
/// Unwraps a result, yielding the content of an [`Err`].
///
/// # Panics
///
/// Panics if the value is an [`Ok`], logging a message provided by the
/// [`Ok`]'s value to a [`tracing::Subscriber`] at an [`ERROR`] level.
///
/// [`ERROR`]: /tracing/0.1/tracing/struct.Level.html#associatedconstant.ERROR
fn unwrap_err_or_log(self) -> E
where
T: fmt::Debug;
/// Unwraps a result, yielding the content of an [`Err`].
///
/// # Panics
///
/// Panics if the value is an [`Ok`], logging the passed message and the
/// content of the [`Ok`] to a [`tracing::Subscriber`] at an [`ERROR`] level.
///
/// [`ERROR`]: /tracing/0.1/tracing/struct.Level.html#associatedconstant.ERROR
fn expect_err_or_log(self, msg: &str) -> E
where
T: fmt::Debug;
}
impl<T, E> ResultExt<T, E> for Result<T, E> {
#[inline]
#[track_caller]
fn unwrap_or_log(self) -> T
where
E: fmt::Debug,
{
match self {
Ok(t) => t,
Err(e) => failed_with("called `Result::unwrap_or_log()` on an `Err` value", &e),
}
}
#[inline]
#[track_caller]
fn expect_or_log(self, msg: &str) -> T
where
E: fmt::Debug,
{
match self {
Ok(t) => t,
Err(e) => failed_with(msg, &e),
}
}
#[inline]
#[track_caller]
fn unwrap_err_or_log(self) -> E
where
T: fmt::Debug,
{
match self {
Ok(t) => failed_with("called `Result::unwrap_err_or_log()` on an `Ok` value", &t),
Err(e) => e,
}
}
#[inline]
#[track_caller]
fn expect_err_or_log(self, msg: &str) -> E
where
T: fmt::Debug,
{
match self {
Ok(t) => failed_with(msg, &t),
Err(e) => e,
}
}
}
//
// Extension trait for Option types.
//
/// Extension trait for Option types.
pub trait OptionExt<T> {
/// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
///
/// In general, because this function may panic, its use is discouraged.
/// Instead, prefer to use pattern matching and handle the [`None`]
/// case explicitly.
///
/// # Panics
///
/// Panics if the self value equals [`None`], logging an error message to a
/// [`tracing::Subscriber`] at an [`ERROR`] level.
fn unwrap_or_log(self) -> T;
/// Unwraps an option, yielding the content of a [`Some`].
///
/// # Panics
///
/// Panics if the value is a [`None`], logging the passed message to a
/// [`tracing::Subscriber`] at an [`ERROR`] level.
fn expect_or_log(self, msg: &str) -> T;
/// Unwraps an option, expecting [`None`] and returning nothing.
///
/// # Panics
///
/// Panics if the value is a [`Some`], logging a message derived from the
/// [`Some`]'s value to a [`tracing::Subscriber`] at an [`ERROR`] level.
fn unwrap_none_or_log(self)
where
T: fmt::Debug;
/// Unwraps an option, expecting [`None`] and returning nothing.
///
/// # Panics
///
/// Panics if the value is a [`Some`], logging the passed message and the
/// content of the [`Some`] to a [`tracing::Subscriber`] at an [`ERROR`] level.
fn expect_none_or_log(self, msg: &str)
where
T: fmt::Debug;
}
impl<T> OptionExt<T> for Option<T> {
#[inline]
#[track_caller]
fn unwrap_or_log(self) -> T {
match self {
Some(val) => val,
None => failed("called `Option::unwrap_or_log()` on a `None` value"),
}
}
#[inline]
#[track_caller]
fn expect_or_log(self, msg: &str) -> T {
match self {
Some(val) => val,
None => failed(msg),
}
}
#[inline]
#[track_caller]
fn unwrap_none_or_log(self)
where
T: fmt::Debug,
{
if let Some(val) = self {
failed_with(
"called `Option::unwrap_none_or_log()` on a `Some` value",
&val,
);
}
}
#[inline]
#[track_caller]
fn expect_none_or_log(self, msg: &str)
where
T: fmt::Debug,
{
if let Some(val) = self {
failed_with(msg, &val);
}
}
}
//
// Helper functions.
//
#[inline(never)]
#[cold]
#[track_caller]
fn failed(msg: &str) -> ! {
#[cfg(feature = "log-location")]
{
let location = std::panic::Location::caller();
tracing::error!(
unwrap.filepath = location.file(),
unwrap.lineno = location.line(),
unwrap.columnno = location.column(),
"{}",
msg
);
}
#[cfg(not(feature = "log-location"))]
tracing::error!("{}", msg);
#[cfg(feature = "panic-quiet")]
panic!();
#[cfg(not(feature = "panic-quiet"))]
panic!("{}", msg)
}
#[inline(never)]
#[cold]
#[track_caller]
fn failed_with(msg: &str, value: &dyn fmt::Debug) -> ! {
#[cfg(feature = "log-location")]
{
let location = std::panic::Location::caller();
tracing::error!(
unwrap.filepath = location.file(),
unwrap.lineno = location.line(),
unwrap.columnno = location.column(),
"{}: {:?}",
msg,
&value
);
}
#[cfg(not(feature = "log-location"))]
tracing::error!("{}: {:?}", msg, &value);
#[cfg(feature = "panic-quiet")]
panic!();
#[cfg(not(feature = "panic-quiet"))]
panic!("{}: {:?}", msg, &value);
}