1extern crate astrolog;
21
22use std::env;
23use std::fs::File;
24use std::error::Error;
25use std::fmt;
26
27use astrolog::handler::console::ConsoleHandler;
28use astrolog::prelude::*;
29
30struct MyError {
31 msg: String,
32 cause: Option<Box<Error>>,
33}
34
35impl MyError {
36 pub fn new(msg: &str) -> MyError {
37 MyError {
38 msg: msg.into(),
39 cause: None,
40 }
41 }
42
43 pub fn with_cause<E: Error + 'static>(mut self, cause: E) -> Self {
44 self.cause = Some(Box::new(cause));
45 self
46 }
47}
48
49impl Error for MyError {
50 fn description(&self) -> &str {
51 &self.msg
52 }
53
54 fn cause(&self) -> Option<&Error> {
55 match &self.cause {
56 Some(c) => Some(c.as_ref()),
57 None => None,
58 }
59 }
60}
61
62impl fmt::Display for MyError {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 write!(f, "{}", self.description())
65 }
66}
67
68impl fmt::Debug for MyError {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 write!(f, "{}", self.description())
71 }
72}
73
74fn main() {
75 let logger = Logger::new()
76 .with_global("OS", env::consts::OS)
77 .with_handler(ConsoleHandler::new().with_levels_range(Level::Info, Level::Emergency));
78
79 let _ = File::open("foo.txt")
80 .map_err(|e| {
81 logger.with_error(&e).error("Simple error opening foo.txt")
82 });
83
84 let _ = File::open("foo.txt")
85 .map_err(|e| {
86 let e_with_trace = MyError::new("Opening foo.txt").with_cause(e);
87 logger.with_error(&e_with_trace).error("Tracing error opening file")
88 });
89
90 let _ = File::open("foo.txt")
91 .map_err(|e| {
92 let e_with_trace = MyError::new("Opening foo.txt").with_cause(MyError::new("second-level error").with_cause(e));
93 logger.with_error(&e_with_trace).error("Deep tracing error opening file")
94 });
95}