-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathlib.rs
More file actions
228 lines (196 loc) · 6.43 KB
/
lib.rs
File metadata and controls
228 lines (196 loc) · 6.43 KB
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Copyright 2024 FastLabs Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A bridge to forward logs from the `log` crate to `logforth`.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_docs)]
use log::Metadata;
use log::Record;
use logforth_core::Logger;
use logforth_core::default_logger;
use logforth_core::kv::Key;
use logforth_core::kv::Value;
use logforth_core::record::FilterCriteria;
fn level_to_level(level: log::Level) -> logforth_core::record::Level {
match level {
log::Level::Error => logforth_core::record::Level::Error,
log::Level::Warn => logforth_core::record::Level::Warn,
log::Level::Info => logforth_core::record::Level::Info,
log::Level::Debug => logforth_core::record::Level::Debug,
log::Level::Trace => logforth_core::record::Level::Trace,
}
}
struct LogCrateLogger(());
impl log::Log for LogCrateLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
forward_enabled(default_logger(), metadata)
}
fn log(&self, record: &Record) {
forward_log(default_logger(), record);
}
fn flush(&self) {
default_logger().flush();
}
}
/// Adapter to use a specific `logforth` logger instance as a `log` crate logger.
pub struct LogProxy<'a>(&'a Logger);
impl<'a> LogProxy<'a> {
/// Create a new `LogProxy` instance.
pub fn new(logger: &'a Logger) -> Self {
Self(logger)
}
}
impl<'a> log::Log for LogProxy<'a> {
fn enabled(&self, metadata: &Metadata) -> bool {
forward_enabled(self.0, metadata)
}
fn log(&self, record: &Record) {
forward_log(self.0, record);
}
fn flush(&self) {
self.0.flush();
}
}
/// Owned version of [`LogProxy`].
pub struct OwnedLogProxy(Logger);
impl OwnedLogProxy {
/// Create a new `OwnedLogProxy` instance.
pub fn new(logger: Logger) -> Self {
Self(logger)
}
}
impl log::Log for OwnedLogProxy {
fn enabled(&self, metadata: &Metadata) -> bool {
forward_enabled(&self.0, metadata)
}
fn log(&self, record: &Record) {
forward_log(&self.0, record);
}
fn flush(&self) {
self.0.flush();
}
}
fn forward_enabled(logger: &Logger, metadata: &Metadata) -> bool {
let criteria = FilterCriteria::builder()
.target(metadata.target())
.level(level_to_level(metadata.level()))
.build();
Logger::enabled(logger, &criteria)
}
fn forward_log(logger: &Logger, record: &Record) {
if !forward_enabled(logger, record.metadata()) {
return;
}
// basic fields
let mut builder = logforth_core::record::Record::builder()
.level(level_to_level(record.level()))
.target(record.target())
.line(record.line());
// optional static fields
builder = if let Some(module_path) = record.module_path_static() {
builder.module_path_static(module_path)
} else {
builder.module_path(record.module_path())
};
builder = if let Some(file) = record.file_static() {
builder.file_static(file)
} else {
builder.file(record.file())
};
// payload
builder = if let Some(payload) = record.args().as_str() {
builder.payload(payload)
} else {
builder.payload(record.args().to_string())
};
// key-values
let mut kvs = Vec::new();
struct KeyValueVisitor<'a, 'b> {
kvs: &'b mut Vec<(log::kv::Key<'a>, log::kv::Value<'a>)>,
}
impl<'a, 'b> log::kv::VisitSource<'a> for KeyValueVisitor<'a, 'b> {
fn visit_pair(
&mut self,
key: log::kv::Key<'a>,
value: log::kv::Value<'a>,
) -> Result<(), log::kv::Error> {
self.kvs.push((key, value));
Ok(())
}
}
let mut visitor = KeyValueVisitor { kvs: &mut kvs };
record.key_values().visit(&mut visitor).unwrap();
let mut new_kvs = Vec::with_capacity(kvs.len());
for (k, v) in kvs.iter() {
new_kvs.push((Key::new_ref(k.as_str()), Value::from_sval2(v)));
}
builder = builder.key_values(new_kvs.as_slice());
Logger::log(logger, &builder.build());
}
/// Set up the log crate global logger.
///
/// This function calls [`log::set_logger`] to set up a `LogCrateProxy` and
/// all logs from log crate will be forwarded to `logforth`'s default logger.
///
/// This should be called early in the execution of a Rust program. Any log events that occur
/// before initialization will be ignored.
///
/// This function will set the global maximum log level to `Trace`. To override this, call
/// [`log::set_max_level`] after this function.
///
/// # Errors
///
/// Return an error if the log crate global logger has already been set.
///
/// # Examples
///
/// ```
/// if let Err(err) = logforth_bridge_log::try_setup() {
/// eprintln!("failed to setup log crate: {err}");
/// }
/// ```
pub fn try_setup() -> Result<(), log::SetLoggerError> {
static LOGGER: LogCrateLogger = LogCrateLogger(());
log::set_logger(&LOGGER)?;
log::set_max_level(log::LevelFilter::Trace);
Ok(())
}
/// Set up the log crate global logger.
///
/// This function calls [`log::set_logger`] to set up a `LogCrateProxy` and
/// all logs from log crate will be forwarded to `logforth`'s default logger.
///
/// This should be called early in the execution of a Rust program. Any log events that occur
/// before initialization will be ignored.
///
/// This function will panic if it is called more than once, or if another library has already
/// initialized the log crate global logger.
///
/// This function will set the global maximum log level to `Trace`. To override this, call
/// [`log::set_max_level`] after this function.
///
/// # Panics
///
/// Panic if the log crate global logger has already been set.
///
/// # Examples
///
/// ```
/// logforth_bridge_log::setup();
/// logforth_core::builder().apply()
/// ```
pub fn setup() {
try_setup().expect(
"logforth_bridge_log::setup must be called before the log crate global logger initialized",
)
}