unwrap_log/
lib.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
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
//! Non-panicking alternatives to `Option` and `Result` unwrapping, which log at warn level.
//!
//! ## Example
//!
//! ```rust
//! use unwrap_log::{OptionExt, ResultExt};
//! use env_logger::Builder;
//! use log::LevelFilter::Warn;
//!
//! Builder::new().filter_level(Warn).init();
//!
//! let x: i32 = None.unwrap_or_default_log();
//! assert_eq!(x, 0);
//!
//! let y: i32 = Err("oops").unwrap_or_default_log();
//! assert_eq!(y, 0);
//! ```
//!
//! Output:
//! ```text
//! [1970-01-01T00:00:00Z WARN  my_crate] src\main.rs:8:23 encountered `None`
//! [1970-01-01T00:00:00Z WARN  my_crate] src\main.rs:11:30 encountered `Err("oops")`
//! ```
#![no_std]

/// Extension trait providing tracing alternatives to `Option` unwrap methods.
pub trait OptionExt {
    /// The type of the "present" output, intended to be `T` for a `Option<T>`.
    type Output;
    /// Returns the contained `Some` value, or logs at the warn level and returns a default value.
    fn unwrap_or_default_log(self) -> Self::Output;
    /// Returns the contained `Some` value, or logs at the warn level and computes a default value from a closure.
    fn unwrap_or_else_log(self, f: impl FnOnce() -> Self::Output) -> Self::Output;
    /// Returns the contained `Some` value, or logs at the warn level and returns the provided default.
    fn unwrap_or_log(self, default: Self::Output) -> Self::Output;
}

/// Extension trait providing tracing alternatives to `Result` unwrap methods.
pub trait ResultExt {
    /// The type of the "successful" output, intended to be `T` for a `Result<T, E>`.
    type Output;
    /// Returns the contained `Ok` value, or logs at the warn level and returns a default value.
    fn unwrap_or_default_log(self) -> Self::Output;
    /// Returns the contained `Ok` value, or logs at the warn level and computes a default value from a closure.
    fn unwrap_or_else_log(self, f: impl FnOnce() -> Self::Output) -> Self::Output;
    /// Returns the contained `Ok` value, or logs at the warn level and returns the provided default.
    fn unwrap_or_log(self, default: Self::Output) -> Self::Output;
}

/// Like `ResultExt` for `Result<T, E>`, but doesn't require `E: Debug`.
///
/// This is provided for users who want to avoid logging sensitive information,
/// or who want to slim down their log files.
pub trait ResultExtNoDbg {
    /// The type of the "successful" output, intended to be `T` for a `Result<T, E>`.
    type Output;
    /// Returns the contained `Ok` value, or logs at the warn level and returns a default value.
    fn unwrap_or_default_log(self) -> Self::Output;
    /// Returns the contained `Ok` value, or logs at the warn level and computes a default value from a closure.
    fn unwrap_or_else_log(self, f: impl FnOnce() -> Self::Output) -> Self::Output;
    /// Returns the contained `Ok` value, or logs at the warn level and returns the provided default.
    fn unwrap_or_log(self, default: Self::Output) -> Self::Output;
}

impl<T: Default> OptionExt for Option<T> {
    type Output = T;

    #[track_caller]
    fn unwrap_or_default_log(self) -> T {
        if let Some(x) = self {
            x
        } else {
            option_error();
            T::default()
        }
    }

    #[track_caller]
    fn unwrap_or_else_log(self, f: impl FnOnce() -> T) -> T {
        if let Some(x) = self {
            x
        } else {
            option_error();
            f()
        }
    }

    #[track_caller]
    fn unwrap_or_log(self, default: T) -> T {
        if let Some(x) = self {
            x
        } else {
            option_error();
            default
        }
    }
}

impl<T: Default, E: core::fmt::Debug> ResultExt for Result<T, E> {
    type Output = T;

    #[track_caller]
    fn unwrap_or_default_log(self) -> T {
        match self {
            Ok(x) => x,
            Err(err) => {
                result_error(&err);
                T::default()
            }
        }
    }

    #[track_caller]
    fn unwrap_or_else_log(self, f: impl FnOnce() -> T) -> T {
        match self {
            Ok(x) => x,
            Err(err) => {
                result_error(&err);
                f()
            }
        }
    }

    #[track_caller]
    fn unwrap_or_log(self, default: T) -> T {
        match self {
            Ok(x) => x,
            Err(err) => {
                result_error(&err);
                default
            }
        }
    }
}

impl<T: Default, E> ResultExtNoDbg for Result<T, E> {
    type Output = T;

    #[track_caller]
    fn unwrap_or_default_log(self) -> T {
        if let Ok(x) = self {
            x
        } else {
            no_dbg_error();
            T::default()
        }
    }

    #[track_caller]
    fn unwrap_or_else_log(self, f: impl FnOnce() -> T) -> T {
        if let Ok(x) = self {
            x
        } else {
            no_dbg_error();
            f()
        }
    }

    #[track_caller]
    fn unwrap_or_log(self, default: T) -> T {
        if let Ok(x) = self {
            x
        } else {
            no_dbg_error();
            default
        }
    }
}

#[cold]
#[inline(never)]
#[track_caller]
fn option_error() {
    let caller = core::panic::Location::caller();
    log::warn!("{caller} encountered `None`");
}

#[cold]
#[inline(never)]
#[track_caller]
fn result_error(err: &dyn core::fmt::Debug) {
    let caller = core::panic::Location::caller();
    log::warn!("{caller} encountered `Err({err:?})`");
}

#[cold]
#[inline(never)]
#[track_caller]
fn no_dbg_error() {
    let caller = core::panic::Location::caller();
    log::warn!("{caller} encountered `Err(_)`");
}