logerr 0.1.0

Seamless error type logging
Documentation
mod error;

/// Helper trait to easily log error types.
///
/// The `print_error` function takes a closure which takes a `&str` and fares with it as necessary
/// to log the error to some usable location. For convenience, logging to stdout, stderr and
/// `log::error!` is already implemented.
///
/// Note that the trait functions pass the error through unmodified, so they can be chained with
/// the usual handling of [`std::result::Result`] types.
///
/// # Developer notes
///
/// We can dump the different impls once [#31844](https://github.com/rust-lang/rust/issues/31844)
/// is stabilized.
pub trait LoggableError<T>: Sized {
    /// Gives a formatted error message derived from `self` to the closure `fun` for
    /// printing/logging as appropriate.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use anyhow;
    /// use crate::LoggableError;
    ///
    /// let my_err: anyhow::Result<&str> = Err(anyhow::anyhow!("Test error"));
    /// my_err
    ///     .print_error(|msg| println!("{msg}"))
    ///     .unwrap();
    /// ```
    fn print_error<F: Fn(&str)>(self, fun: F) -> Self;

    /// Convenienve function, calls `print_error` with the closure `|msg| log::error!("{}", msg)`.
    /// Requires the "log" feature.
    #[cfg(not(feature = "log"))]
    fn to_log(self) -> Self;
    #[cfg(feature = "log")]
    fn to_log(self) -> Self {
        self.print_error(|msg| log::error!("{}", msg))
    }

    /// Convenienve function, calls `print_error` with the closure `|msg| eprintln!("{}", msg)`.
    fn to_stderr(self) -> Self {
        self.print_error(|msg| eprintln!("{}", msg))
    }

    /// Convenienve function, calls `print_error` with the closure `|msg| println!("{}", msg)`.
    fn to_stdout(self) -> Self {
        self.print_error(|msg| println!("{}", msg))
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn it_works() {
    }
}