/* Astrolog, a logging framework for Rust Copyright (C) 2019 Alessandro Pellizzari This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ extern crate astrolog; use std::env; use std::fs::File; use std::error::Error; use std::fmt; use astrolog::handler::console::ConsoleHandler; use astrolog::prelude::*; struct MyError { msg: String, cause: Option>, } impl MyError { pub fn new(msg: &str) -> MyError { MyError { msg: msg.into(), cause: None, } } pub fn with_cause(mut self, cause: E) -> Self { self.cause = Some(Box::new(cause)); self } } impl Error for MyError { fn description(&self) -> &str { &self.msg } fn cause(&self) -> Option<&Error> { match &self.cause { Some(c) => Some(c.as_ref()), None => None, } } } impl fmt::Display for MyError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl fmt::Debug for MyError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } fn main() { let logger = Logger::new() .with_global("OS", env::consts::OS) .with_handler(ConsoleHandler::new().with_levels_range(Level::Info, Level::Emergency)); let _ = File::open("foo.txt") .map_err(|e| { logger.with_error(&e).error("Simple error opening foo.txt") }); let _ = File::open("foo.txt") .map_err(|e| { let e_with_trace = MyError::new("Opening foo.txt").with_cause(e); logger.with_error(&e_with_trace).error("Tracing error opening file") }); let _ = File::open("foo.txt") .map_err(|e| { let e_with_trace = MyError::new("Opening foo.txt").with_cause(MyError::new("second-level error").with_cause(e)); logger.with_error(&e_with_trace).error("Deep tracing error opening file") }); }