result_logger/lib.rs
1//! A utility crate for enhancing `Result<T, E>` with logging capabilities.
2//!
3//! This crate provides the `ResultLogging` trait, which extends `Result<T, E>` with methods to
4//! log errors at different log levels using the `log` crate.
5//!
6//! # Example Usage
7//! ```
8//! use log::{LevelFilter, info};
9//! use simple_logger::SimpleLogger;
10//! use result_logger::ResultLogger;
11//!
12//! fn example_function() -> Result<(), &'static str> {
13//! Err("Something went wrong!")
14//! }
15//!
16//! fn main() {
17//! SimpleLogger::new().init().unwrap();
18//! let _ = example_function().error(); // Logs the error message at the error level
19//! }
20//! ```
21
22use log::{debug, error, info, trace, warn};
23
24/// A trait that provides logging capabilities for `Result<T, E>`.
25///
26/// This trait allows logging the `Err` variant of a `Result` at various log levels
27/// without consuming the result, enabling error tracking without affecting the
28/// control flow.
29pub trait ResultLogger {
30 /// Logs an error message at the TRACE level if the `Result` is an `Err`.
31 fn trace(self) -> Self;
32 /// Logs an error message at the DEBUG level if the `Result` is an `Err`.
33 fn debug(self) -> Self;
34 /// Logs an error message at the INFO level if the `Result` is an `Err`.
35 fn info(self) -> Self;
36 /// Logs an error message at the WARN level if the `Result` is an `Err`.
37 fn warn(self) -> Self;
38 /// Logs an error message at the ERROR level if the `Result` is an `Err`.
39 fn error(self) -> Self;
40}
41
42impl<T, E: std::fmt::Display> ResultLogger for Result<T, E> {
43 fn trace(self) -> Self {
44 self.inspect_err(|e| trace!("{}", e))
45 }
46
47 fn debug(self) -> Self {
48 self.inspect_err(|e| debug!("{}", e))
49 }
50
51 fn info(self) -> Self {
52 self.inspect_err(|e| info!("{}", e))
53 }
54
55 fn warn(self) -> Self {
56 self.inspect_err(|e| warn!("{}", e))
57 }
58
59 fn error(self) -> Self {
60 self.inspect_err(|e| error!("{}", e))
61 }
62}
63
64#[cfg(test)]
65mod tests {}