1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use std::error::Error;
use err_context::prelude::*;
use log::{log, Level};
pub type AnyError = Box<dyn Error + Send + Sync>;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[non_exhaustive]
pub enum ErrorLogFormat {
MultiLine,
SingleLine,
}
pub fn log_error(level: Level, target: &str, e: &AnyError, format: ErrorLogFormat) {
match format {
ErrorLogFormat::MultiLine => {
for cause in e.chain() {
log!(target: target, level, "{}", cause);
}
}
ErrorLogFormat::SingleLine => {
log!(target: target, level, "{}", e.display("; "));
}
}
}
#[macro_export]
macro_rules! log_error {
($level: ident, $descr: expr => $err: expr) => {
$crate::log_error!(@SingleLine, $level, $err.context($descr).into());
};
($level: ident, $err: expr) => {
$crate::log_error!(@SingleLine, $level, $err);
};
(multi $level: ident, $descr: expr => $err: expr) => {
$crate::log_error!(@MultiLine, $level, $err.context($descr).into());
};
(multi $level: ident, $err: expr) => {
$crate::log_error!(@MultiLine, $level, $err);
};
(@$format: ident, $level: ident, $err: expr) => {
$crate::error::log_error(
$crate::macro_support::Level::$level,
module_path!(),
&$err,
$crate::error::ErrorLogFormat::$format,
);
};
}
pub fn log_errors<R, F>(target: &str, f: F) -> Result<R, AnyError>
where
F: FnOnce() -> Result<R, AnyError>,
{
let result = f();
if let Err(ref e) = result {
log_error(Level::Error, target, e, ErrorLogFormat::MultiLine);
}
result
}
#[cfg(test)]
mod tests {
use std::fmt::{Display, Formatter, Result as FmtResult};
use super::*;
#[derive(Copy, Clone, Debug)]
struct Dummy;
impl Display for Dummy {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
write!(fmt, "Dummy error")
}
}
impl Error for Dummy {}
#[test]
fn log_error_macro() {
let err = Dummy;
log_error!(Debug, err.into());
log_error!(Debug, &err.into());
log_error!(Debug, err.context("Another level").into());
log_error!(Debug, "Another level" => err);
let multi_err = err.context("Another level").into();
log_error!(multi Info, multi_err);
}
}