From cfffe189f9e5d80408d65dfec4bb9a6e73786bdd Mon Sep 17 00:00:00 2001 From: David Greenberg Date: Tue, 5 Sep 2017 21:07:31 -0600 Subject: [PATCH] Added support for quickmain to use `log` crate. * Added crate feature `quickmain_log` When `quickmain_log` is enabled, the `quick_main!` entry point writes the terminating error chain to `log::error!` instead of stdout. --- CHANGELOG.md | 1 + Cargo.toml | 2 ++ src/lib.rs | 5 +++++ src/quick_main.rs | 22 ++++++++++++++++++---- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed0f12e3a..a2b9d035d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - [Mask the `quick_error` macro from the doc](https://github.com/rust-lang-nursery/error-chain/pull/210) - [Make generated `ErrorKind` enums non-exhaustive](https://github.com/rust-lang-nursery/error-chain/pull/193) - All 0.11.0-rc.2 changes +- [Allow users of `quick_main!` to use the `log` crate](https://github.com/rust-lang-nursery/error-chain/pull/216) # 0.11.0-rc.2 diff --git a/Cargo.toml b/Cargo.toml index 25b8cad0b..7299deb5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,9 @@ travis-ci = { repository = "rust-lang-nursery/error-chain" } [features] default = ["backtrace", "example_generated"] +quickmain_log = ["log"] example_generated = [] [dependencies] backtrace = { version = "0.3", optional = true } +log = {version = "0.3", optional = true } diff --git a/src/lib.rs b/src/lib.rs index d0881fcef..e426e6480 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -540,6 +540,10 @@ #[cfg(feature = "backtrace")] extern crate backtrace; +#[cfg(feature = "quickmain_log")] +#[macro_use] +extern crate log; + use std::error; use std::iter::Iterator; #[cfg(feature = "backtrace")] @@ -559,6 +563,7 @@ mod error_chain; #[macro_use] mod quick_main; pub use quick_main::ExitCode; +pub use quick_main::print_quickmain_error; #[cfg(feature = "example_generated")] pub mod example_generated; diff --git a/src/quick_main.rs b/src/quick_main.rs index f81e7d704..0e00aafd0 100644 --- a/src/quick_main.rs +++ b/src/quick_main.rs @@ -42,13 +42,10 @@ macro_rules! quick_main { ($main:expr) => { fn main() { - use ::std::io::Write; - ::std::process::exit(match $main() { Ok(ret) => $crate::ExitCode::code(ret), Err(ref e) => { - write!(&mut ::std::io::stderr(), "{}", $crate::ChainedError::display_chain(e)) - .expect("Error writing to stderr"); + { $crate::print_quickmain_error(e); } 1 } @@ -75,3 +72,20 @@ impl ExitCode for () { 0 } } + +/// When using `quick_main!`, prints the error if the program doesn't terminate successfully. +pub fn print_quickmain_error>(e: &E) { + print_error_helper(e); +} + +#[cfg(not(feature = "quickmain_log"))] +fn print_error_helper>(e: &E) { + use ::std::io::Write; + write!(&mut ::std::io::stderr(), "{}", ::ChainedError::display_chain(e)) + .expect("Error writing to stderr"); +} + +#[cfg(feature = "quickmain_log")] +fn print_error_helper>(e: &E) { + { error!("{}", ::ChainedError::display_chain(e)) } +}