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
#![doc = include_str!("../README.md")]
use core::fmt::{Debug, Display};
use log::{logger, Level};
pub trait LogError<T, E>: Sized {
fn log_level_with<F: FnOnce(E) -> String>(self, level: Level, cb: F) -> Option<T>;
#[inline(always)]
#[track_caller]
fn log_error_with<F: FnOnce(E) -> String>(self, cb: F) -> Option<T> {
self.log_level_with(Level::Error, cb)
}
#[inline(always)]
#[track_caller]
fn log_warn_with<F: FnOnce(E) -> String>(self, cb: F) -> Option<T> {
self.log_level_with(Level::Warn, cb)
}
#[inline(always)]
#[track_caller]
fn log_error(self, msg: &str) -> Option<T>
where
E: Display,
{
self.log_error_with(|err| format!("{msg}: {err}"))
}
#[inline(always)]
#[track_caller]
fn log_error_detail(self, msg: &str) -> Option<T>
where
E: Debug,
{
self.log_error_with(|err| format!("{msg}: {err:#?}"))
}
#[inline(always)]
#[track_caller]
fn log_warn(self, msg: &str) -> Option<T>
where
E: Display,
{
self.log_warn_with(|err| format!("{msg}: {err}"))
}
#[inline(always)]
#[track_caller]
fn log_warn_detail(self, msg: &str) -> Option<T>
where
E: Debug,
{
self.log_warn_with(|err| format!("{msg}: {err:#?}"))
}
}
impl<T, E> LogError<T, E> for Result<T, E> {
#[inline(always)]
#[track_caller]
fn log_level_with<F: FnOnce(E) -> String>(self, level: Level, cb: F) -> Option<T> {
match self {
Ok(res) => Some(res),
Err(err) => {
log_message(level, cb(err));
None
}
}
}
}
impl<T> LogError<T, &'static str> for Option<T> {
#[inline(always)]
#[track_caller]
fn log_level_with<F: FnOnce(&'static str) -> String>(self, level: Level, cb: F) -> Option<T> {
match self {
Some(res) => Some(res),
None => {
log_message(level, cb("None"));
None
}
}
}
}
#[track_caller]
fn log_message(level: Level, msg: String) {
let loc = std::panic::Location::caller();
let file = loc.file();
let module = &file[file
.rfind(|c| c == '/' || c == '\\')
.map(|x| 1 + x)
.unwrap_or(0)..];
logger().log(
&log::Record::builder()
.args(format_args!("{msg}"))
.file(Some(file))
.line(Some(loc.line()))
.level(level)
.module_path(Some(module))
.build(),
);
}