tracing-result 0.0.2

An ergonomic wrapper making it easy to emit tracing messages on errors.
Documentation
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
#![cfg_attr(unstable_never_type, feature(never_type))]
#![cfg_attr(unstable_try_trait_v2, feature(try_trait_v2))]
#![cfg_attr(unstable_try_trait_v2_residual, feature(try_trait_v2_residual))]

//! A library for ergonomic error handling with tracing support.
//!
//! This crate provides [`TracingResult`], a wrapper around [`Result`] that automatically
//! emits tracing messages at configurable log levels when results are unpacked via the `?` operator.
//! It integrates seamlessly with Rust's [`Try`] trait.
//!
//! # Overview
//!
//! The [`Trace`] trait extends [`Result<T, E>`] with methods that convert a [`Result`] into a [`TracingResult`]
//! with a custom message. The message is logged automatically when the [`TracingResult`] is used with
//! the `?` operator.
//!
//! There are two families of methods:
//! - **`or_*` methods** (`or_warn`, `or_error`, `or_debug`, `or_trace`): Log the message when an **Err** is unpacked
//! - **`and_*` methods** (`and_warn`, `and_error`, `and_debug`, `and_trace`): Log the message when an **Ok** is unpacked
//!
//! # Example
//!
//! ```
//! use std::io;
//! use tracing_result::Trace;
//!
//! fn might_fail() -> io::Result<u32> {
//!     Err(io::Error::other("something went wrong"))
//! }
//!
//! fn compute() -> io::Result<u32> {
//!     // If might_fail() returns Err, "Failed to compute value" will be logged as a warning
//!     might_fail().or_warn("Failed to compute value")?;
//!     Ok(42)
//! }
//!
//! fn unexpected_success() -> io::Result<u32> {
//!     // If Ok is returned, "Unexpected: computation succeeded" will be logged as a warning
//!     Ok(42).and_warn("Unexpected: computation succeeded")?;
//!     Ok(42)
//! }
//! ```
//!
//! # Features
//!
//! - Automatic tracing on result propagation via `?`
//! - Support for all [`tracing`] log levels: ERROR, WARN, INFO, DEBUG, TRACE
//! - Compatible with Rust's unstable `Try` trait v2 (when enabled)

use std::{
    error::Error,
    ops::{ControlFlow, FromResidual, Residual, Try},
};
use tracing::Level;
use try_v2::Extract;

/// Configuration for tracing log level and message.
///
/// This struct holds the log level and message that will be emitted when a
/// [`TracingResult`] is unpacked via the `?` operator.
///
/// # Fields
///
/// - `level`: The [`tracing::Level`] at which to log the message
/// - `message`: The static string message to log
#[derive(Debug, Clone, Copy)]
pub struct TracingConfig {
    /// The tracing level to use when logging.
    pub level: Level,
    /// The message to log.
    pub message: &'static str,
}

/// A result type that emits tracing messages at configurable log levels.
///
/// [`TracingResult`] acts like the standard [`Result`] type, adding the ability to
/// associate a custom message that is logged when the result is unpacked via the `?` operator.
/// The log level (ERROR, WARN, INFO, DEBUG, or TRACE) is determined by which [`Trace`] trait
/// method was used to construct it.
///
/// It is usually constructed via methods from the [`Trace`] trait and rarely returned
/// directly - `?` will work in a block which returns [`Result`].
///
/// # Example
///
/// ```
/// use std::io;
/// use tracing_result::{Trace, TracingResult};
///
/// fn divide(a: i32, b: i32) -> io::Result<i32> {
///     if b == 0 {
///         let oops: TracingResult<_, _> = Err(io::Error::other("division by zero"))
///             .or_warn("Cannot divide by zero");
///         oops?;
///     }
///     Ok(a / b)
/// }
/// ```
pub enum TracingResult<T, E> {
    /// Success case containing the result value and optional tracing configuration.
    Ok {
        val: T,
        config: Option<TracingConfig>,
    },
    /// Error case containing both the error and optional tracing configuration.
    ///
    /// If `config` is present, the message is logged at the specified level
    /// when the error is propagated using the `?` operator.
    Err {
        err: E,
        config: Option<TracingConfig>,
    },
}

/// Calling any of the extract functions *will emit* the enclosed tracing entries related
/// to the relevant variant.
///
/// E.g.
/// - `.unwrap()` will emit any entries stored on the `Ok` variant but *not* any entries stored
///   on the `Err` variant.
impl<T, E: Error> Extract<T> for TracingResult<T, E> {}

impl<T, E: Error> TracingResult<T, E> {
    /// Converts from TracingResult<T, E> to Option<T>, emitting any tracing entry stored
    /// in `Ok` variant (via `and_...()`) the process.
    ///
    /// Converts self into an Option<T>, consuming self, and converting the error to None, if any.
    pub fn ok(self) -> Option<T> {
        self.output()
    }

    /// Converts from TracingResult<T, E> to Option<E>, emitting any tracing  entry stored
    /// in `Err` variant (via `or_...()`) the process.
    ///
    /// Converts self into an Option<E>, consuming self, and discarding the success value, if any.
    pub fn err(self) -> Option<E> {
        match self.branch() {
            ControlFlow::Continue(_) => None,
            ControlFlow::Break(TracingResult::Err { err, .. }) => Some(err),
        }
    }
}

impl<T, E: Error> Try for TracingResult<T, E> {
    type Output = T;

    type Residual = TracingResult<!, E>;

    fn from_output(output: Self::Output) -> Self {
        Self::Ok {
            val: output,
            config: None,
        }
    }

    /// Executes the `Try` branch operation, logging messages based on config.
    ///
    /// When the result is [`Ok`] with a config, the message is logged at the specified level.
    /// When the result is [`Err`] with a config, the message is logged at the specified level
    /// with error info.
    ///
    /// This is the mechanism that enables automatic tracing when using the `?` operator.
    #[track_caller]
    #[inline(always)]
    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
        match self {
            TracingResult::Ok { val, config } => {
                if let Some(cfg) = config {
                    match cfg.level {
                        Level::ERROR => tracing::error!("{}", cfg.message),
                        Level::WARN => tracing::warn!("{}", cfg.message),
                        Level::INFO => tracing::info!("{}", cfg.message),
                        Level::DEBUG => tracing::debug!("{}", cfg.message),
                        Level::TRACE => tracing::trace!("{}", cfg.message),
                    }
                }
                ControlFlow::Continue(val)
            }
            TracingResult::Err { err, config } => {
                if let Some(cfg) = config {
                    match cfg.level {
                        Level::ERROR => tracing::error!(error = err.to_string(), "{}", cfg.message),
                        Level::WARN => tracing::warn!(error = err.to_string(), "{}", cfg.message),
                        Level::INFO => tracing::info!(error = err.to_string(), "{}", cfg.message),
                        Level::DEBUG => tracing::debug!(error = err.to_string(), "{}", cfg.message),
                        Level::TRACE => tracing::trace!(error = err.to_string(), "{}", cfg.message),
                    }
                }
                ControlFlow::Break(TracingResult::Err { err, config })
            }
        }
    }
}

/// TODO: #3 double emission
impl<T, E: Error> FromResidual for TracingResult<T, E> {
    fn from_residual(residual: <Self as Try>::Residual) -> Self {
        match residual {
            TracingResult::Ok { .. } => unreachable!(),
            TracingResult::Err { err, config } => Self::Err { err, config },
        }
    }
}

impl<T, E: Error> FromResidual<TracingResult<!, E>> for Result<T, E> {
    fn from_residual(residual: TracingResult<!, E>) -> Self {
        match residual {
            TracingResult::Ok { .. } => unreachable!(),
            TracingResult::Err { err, .. } => Result::Err(err),
        }
    }
}

impl<T, E: Error> Residual<T> for TracingResult<!, E> {
    type TryType = TracingResult<T, E>;
}

/// A trait for converting results into tracing results with custom log messages.
///
/// This trait extends [`Result<T, E>`] with methods that attach custom messages at various
/// log levels. When the resulting [`TracingResult`] is used with the `?` operator, the message
/// will be automatically logged via the [`tracing`] macro corresponding to the chosen level.
///
/// # Method Families
///
/// - **`or_*`** (`or_warn`, `or_error`, `or_debug`, `or_trace`): Attach a message that logs when **Err** is unpacked
/// - **`and_*`** (`and_warn`, `and_error`, `and_debug`, `and_trace`): Attach a message that logs when **Ok** is unpacked
///
/// # Example
///
/// ```
/// use std::io;
/// use tracing_result::Trace;
///
/// fn might_fail() -> io::Result<i32> {
///     Err(io::Error::other("network error"))
/// }
///
/// fn process() -> io::Result<i32> {
///     // Logs "Failed to fetch data" at WARN level if might_fail() returns Err
///     let result = might_fail().or_warn("Failed to fetch data");
///     result?;
///     Ok(42)
/// }
///
/// fn unexpected() -> io::Result<i32> {
///     // Logs "Unexpected success" at WARN level when Ok is unpacked
///     Ok(42).and_warn("Unexpected success")?;
///     Ok(42)
/// }
/// ```
pub trait Trace<T, E: Error> {
    /// Attaches a warning message to this result.
    ///
    /// Converts the [`Result`] into a [`TracingResult`] that will log the
    /// provided message via [`tracing::warn`] if an error occurs and is
    /// propagated with the `?` operator.
    ///
    /// # Example
    ///
    /// ```
    /// use std::io;
    /// use tracing_result::Trace;
    ///
    /// let result: io::Result<i32> = Err(io::Error::other("io error"));
    /// let tracing_result = result.or_warn("File read failed");
    ///
    /// // When tracing_result? is used, "File read failed" will be logged
    /// ```
    fn or_warn(self, name: &'static str) -> TracingResult<T, E>;

    /// Attaches a warning message to this result that logs when Ok is unpacked.
    ///
    /// Converts the [`Result`] into a [`TracingResult`] that will log the
    /// provided message via [`tracing::warn`] if the result is [`Ok`] and is
    /// propagated with the `?` operator.
    ///
    /// # Example
    ///
    /// ```
    /// use std::io;
    /// use tracing_result::Trace;
    ///
    /// let result: io::Result<i32> = Ok(42);
    /// let tracing_result = result.and_warn("Unexpected success");
    ///
    /// // When tracing_result? is used, "Unexpected success" will be logged
    /// ```
    fn and_warn(self, name: &'static str) -> TracingResult<T, E>;

    /// Attaches an error-level message to this result.
    ///
    /// Converts the [`Result`] into a [`TracingResult`] that will log the
    /// provided message via [`tracing::error`] if an error occurs and is
    /// propagated with the `?` operator.
    ///
    /// # Example
    ///
    /// ```
    /// use std::io;
    /// use tracing_result::Trace;
    ///
    /// let result: io::Result<i32> = Err(io::Error::other("io error"));
    /// let tracing_result = result.or_error("Critical failure");
    ///
    /// // When tracing_result? is used, "Critical failure" will be logged at ERROR level
    /// ```
    fn or_error(self, name: &'static str) -> TracingResult<T, E>;

    /// Attaches an error-level message to this result that logs when Ok is unpacked.
    ///
    /// Converts the [`Result`] into a [`TracingResult`] that will log the
    /// provided message via [`tracing::error`] if the result is [`Ok`] and is
    /// propagated with the `?` operator.
    ///
    /// # Example
    ///
    /// ```
    /// use std::io;
    /// use tracing_result::Trace;
    ///
    /// let result: io::Result<i32> = Ok(42);
    /// let tracing_result = result.and_error("This should not succeed");
    ///
    /// // When tracing_result? is used, "This should not succeed" will be logged at ERROR level
    /// ```
    fn and_error(self, name: &'static str) -> TracingResult<T, E>;

    /// Attaches a debug-level message to this result.
    ///
    /// Converts the [`Result`] into a [`TracingResult`] that will log the
    /// provided message via [`tracing::debug`] if an error occurs and is
    /// propagated with the `?` operator.
    ///
    /// # Example
    ///
    /// ```
    /// use std::io;
    /// use tracing_result::Trace;
    ///
    /// let result: io::Result<i32> = Err(io::Error::other("io error"));
    /// let tracing_result = result.or_debug("Debug: operation failed");
    ///
    /// // When tracing_result? is used, "Debug: operation failed" will be logged at DEBUG level
    /// ```
    fn or_debug(self, name: &'static str) -> TracingResult<T, E>;

    /// Attaches a debug-level message to this result that logs when Ok is unpacked.
    ///
    /// Converts the [`Result`] into a [`TracingResult`] that will log the
    /// provided message via [`tracing::debug`] if the result is [`Ok`] and is
    /// propagated with the `?` operator.
    ///
    /// # Example
    ///
    /// ```
    /// use std::io;
    /// use tracing_result::Trace;
    ///
    /// let result: io::Result<i32> = Ok(42);
    /// let tracing_result = result.and_debug("Debug: operation succeeded");
    ///
    /// // When tracing_result? is used, "Debug: operation succeeded" will be logged at DEBUG level
    /// ```
    fn and_debug(self, name: &'static str) -> TracingResult<T, E>;

    /// Attaches a trace-level message to this result.
    ///
    /// Converts the [`Result`] into a [`TracingResult`] that will log the
    /// provided message via [`tracing::trace`] if an error occurs and is
    /// propagated with the `?` operator.
    ///
    /// # Example
    ///
    /// ```
    /// use std::io;
    /// use tracing_result::Trace;
    ///
    /// let result: io::Result<i32> = Err(io::Error::other("io error"));
    /// let tracing_result = result.or_trace("Trace: minor issue detected");
    ///
    /// // When tracing_result? is used, "Trace: minor issue detected" will be logged at TRACE level
    /// ```
    fn or_trace(self, name: &'static str) -> TracingResult<T, E>;

    /// Attaches a trace-level message to this result that logs when Ok is unpacked.
    ///
    /// Converts the [`Result`] into a [`TracingResult`] that will log the
    /// provided message via [`tracing::trace`] if the result is [`Ok`] and is
    /// propagated with the `?` operator.
    ///
    /// # Example
    ///
    /// ```
    /// use std::io;
    /// use tracing_result::Trace;
    ///
    /// let result: io::Result<i32> = Ok(42);
    /// let tracing_result = result.and_trace("Trace: operation completed");
    ///
    /// // When tracing_result? is used, "Trace: operation completed" will be logged at TRACE level
    /// ```
    fn and_trace(self, name: &'static str) -> TracingResult<T, E>;
}

impl<T, E: Error> Trace<T, E> for Result<T, E> {
    fn or_warn(self, name: &'static str) -> TracingResult<T, E> {
        match self {
            Ok(val) => TracingResult::Ok { val, config: None },
            Err(err) => TracingResult::Err {
                err,
                config: Some(TracingConfig {
                    level: Level::WARN,
                    message: name,
                }),
            },
        }
    }

    fn and_warn(self, name: &'static str) -> TracingResult<T, E> {
        match self {
            Ok(val) => TracingResult::Ok {
                val,
                config: Some(TracingConfig {
                    level: Level::WARN,
                    message: name,
                }),
            },
            Err(err) => TracingResult::Err { err, config: None },
        }
    }

    fn or_error(self, name: &'static str) -> TracingResult<T, E> {
        match self {
            Ok(val) => TracingResult::Ok { val, config: None },
            Err(err) => TracingResult::Err {
                err,
                config: Some(TracingConfig {
                    level: Level::ERROR,
                    message: name,
                }),
            },
        }
    }

    fn and_error(self, name: &'static str) -> TracingResult<T, E> {
        match self {
            Ok(val) => TracingResult::Ok {
                val,
                config: Some(TracingConfig {
                    level: Level::ERROR,
                    message: name,
                }),
            },
            Err(err) => TracingResult::Err { err, config: None },
        }
    }

    fn or_debug(self, name: &'static str) -> TracingResult<T, E> {
        match self {
            Ok(val) => TracingResult::Ok { val, config: None },
            Err(err) => TracingResult::Err {
                err,
                config: Some(TracingConfig {
                    level: Level::DEBUG,
                    message: name,
                }),
            },
        }
    }

    fn and_debug(self, name: &'static str) -> TracingResult<T, E> {
        match self {
            Ok(val) => TracingResult::Ok {
                val,
                config: Some(TracingConfig {
                    level: Level::DEBUG,
                    message: name,
                }),
            },
            Err(err) => TracingResult::Err { err, config: None },
        }
    }

    fn or_trace(self, name: &'static str) -> TracingResult<T, E> {
        match self {
            Ok(val) => TracingResult::Ok { val, config: None },
            Err(err) => TracingResult::Err {
                err,
                config: Some(TracingConfig {
                    level: Level::TRACE,
                    message: name,
                }),
            },
        }
    }

    fn and_trace(self, name: &'static str) -> TracingResult<T, E> {
        match self {
            Ok(val) => TracingResult::Ok {
                val,
                config: Some(TracingConfig {
                    level: Level::TRACE,
                    message: name,
                }),
            },
            Err(err) => TracingResult::Err { err, config: None },
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io;

    use tracing_test::traced_test;

    use super::*;

    /// Tests that `or_warn` on an Ok result does not log.
    #[traced_test]
    #[test]
    fn or_warn_ok() {
        fn no_error() -> io::Result<()> {
            Ok(()).or_warn("stuff")?;
            Ok(())
        }

        assert!(no_error().is_ok());
        assert!(!logs_contain("stuff"));
    }

    /// Tests that `or_warn` on an Err result logs the warning message.
    #[traced_test]
    #[test]
    fn or_warn_err() {
        fn err() -> io::Result<()> {
            Err(io::Error::other("oops")).or_warn("stuff")?;
            Ok(())
        }

        assert!(err().is_err());
        assert!(!logs_contain("name"));
        assert!(logs_contain("stuff"));
    }

    /// Tests that `and_warn` on an Ok result logs the warning message.
    #[traced_test]
    #[test]
    fn and_warn_ok() {
        fn ok() -> io::Result<()> {
            Ok(()).and_warn("ok warn")?;
            Ok(())
        }

        assert!(ok().is_ok());
        assert!(logs_contain("ok warn"));
    }

    /// Tests that `and_warn` on an Err result does not log.
    #[traced_test]
    #[test]
    fn and_warn_err() {
        fn err() -> io::Result<()> {
            Err(io::Error::other("oops")).and_warn("should not log")?;
            Ok(())
        }

        assert!(err().is_err());
        assert!(!logs_contain("should not log"));
    }

    /// Tests that `or_error` on an Ok result does not log.
    #[traced_test]
    #[test]
    fn or_error_ok() {
        fn no_error() -> io::Result<()> {
            Ok(()).or_error("should not log")?;
            Ok(())
        }

        assert!(no_error().is_ok());
        assert!(!logs_contain("should not log"));
    }

    /// Tests that `or_error` on an Err result logs at ERROR level.
    #[traced_test]
    #[test]
    fn or_error_err() {
        fn err() -> io::Result<()> {
            Err(io::Error::other("oops")).or_error("error message")?;
            Ok(())
        }

        assert!(err().is_err());
        assert!(logs_contain("error message"));
    }

    /// Tests that `and_error` on an Ok result logs at ERROR level.
    #[traced_test]
    #[test]
    fn and_error_ok() {
        fn ok() -> io::Result<()> {
            Ok(()).and_error("error on ok")?;
            Ok(())
        }

        assert!(ok().is_ok());
        assert!(logs_contain("error on ok"));
    }

    /// Tests that `and_error` on an Err result does not log.
    #[traced_test]
    #[test]
    fn and_error_err() {
        fn err() -> io::Result<()> {
            Err(io::Error::other("oops")).and_error("should not log")?;
            Ok(())
        }

        assert!(err().is_err());
        assert!(!logs_contain("should not log"));
    }

    /// Tests that `or_debug` on an Ok result does not log.
    #[traced_test]
    #[test]
    fn or_debug_ok() {
        fn no_error() -> io::Result<()> {
            Ok(()).or_debug("should not log")?;
            Ok(())
        }

        assert!(no_error().is_ok());
        assert!(!logs_contain("should not log"));
    }

    /// Tests that `or_debug` on an Err result logs at DEBUG level.
    #[traced_test]
    #[test]
    fn or_debug_err() {
        fn err() -> io::Result<()> {
            Err(io::Error::other("oops")).or_debug("debug message")?;
            Ok(())
        }

        assert!(err().is_err());
        assert!(logs_contain("debug message"));
    }

    /// Tests that `and_debug` on an Ok result logs at DEBUG level.
    #[traced_test]
    #[test]
    fn and_debug_ok() {
        fn ok() -> io::Result<()> {
            Ok(()).and_debug("debug on ok")?;
            Ok(())
        }

        assert!(ok().is_ok());
        assert!(logs_contain("debug on ok"));
    }

    /// Tests that `and_debug` on an Err result does not log.
    #[traced_test]
    #[test]
    fn and_debug_err() {
        fn err() -> io::Result<()> {
            Err(io::Error::other("oops")).and_debug("should not log")?;
            Ok(())
        }

        assert!(err().is_err());
        assert!(!logs_contain("should not log"));
    }

    /// Tests that `or_trace` on an Ok result does not log.
    #[traced_test]
    #[test]
    fn or_trace_ok() {
        fn no_error() -> io::Result<()> {
            Ok(()).or_trace("should not log")?;
            Ok(())
        }

        assert!(no_error().is_ok());
        assert!(!logs_contain("should not log"));
    }

    /// Tests that `or_trace` on an Err result logs at TRACE level.
    #[traced_test]
    #[test]
    fn or_trace_err() {
        fn err() -> io::Result<()> {
            Err(io::Error::other("oops")).or_trace("trace message")?;
            Ok(())
        }

        assert!(err().is_err());
        assert!(logs_contain("trace message"));
    }

    /// Tests that `and_trace` on an Ok result logs at TRACE level.
    #[traced_test]
    #[test]
    fn and_trace_ok() {
        fn ok() -> io::Result<()> {
            Ok(()).and_trace("trace on ok")?;
            Ok(())
        }

        assert!(ok().is_ok());
        assert!(logs_contain("trace on ok"));
    }

    /// Tests that `and_trace` on an Err result does not log.
    #[traced_test]
    #[test]
    fn and_trace_err() {
        fn err() -> io::Result<()> {
            Err(io::Error::other("oops")).and_trace("should not log")?;
            Ok(())
        }

        assert!(err().is_err());
        assert!(!logs_contain("should not log"));
    }

    /// Tests that `ok` on an Ok(v) with no log entry returns Some(v) and does not emit.
    #[traced_test]
    #[test]
    fn ok_or_ok() {
        let good = io::Result::Ok(5).or_warn("should not log");
        let v = good.ok();
        assert_eq!(v, Some(5));
        assert!(!logs_contain("should not log"));
    }

    #[traced_test]
    #[test]
    fn ok_and_ok() {
        let good = io::Result::Ok(5).and_warn("should log");
        let v = good.ok();
        assert_eq!(v, Some(5));
        assert!(logs_contain("should log"));
    }

    #[traced_test]
    #[test]
    fn err_or_err() {
        let err: TracingResult<i32, _> = Err(io::Error::other("oops")).or_warn("should log");
        let v = err.err();
        assert_eq!(v.map(|e| e.to_string()), Some("oops".to_string()));
        assert!(logs_contain("should log"));
    }

    #[traced_test]
    #[test]
    fn err_and_err() {
        let err: TracingResult<i32, _> = Err(io::Error::other("oops")).and_warn("should not log");
        let v = err.err();
        assert_eq!(v.map(|e| e.to_string()), Some("oops".to_string()));
        assert!(!logs_contain("should not log"));
    }
}