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
use lazy_static::lazy_static;
use std::sync::{Once, RwLock};
use log::Log;
struct SettableLog {
inner: RwLock<Option<Box<dyn Log>>>,
}
lazy_static! {
static ref SETTABLE_LOG: SettableLog = SettableLog {
inner: RwLock::new(None)
};
}
impl SettableLog {
fn set(&self, logger: Box<dyn Log>) {
let mut write_lock = self.inner.write().unwrap();
*write_lock = Some(logger);
}
fn unset(&self) {
let mut write_lock = self.inner.write().unwrap();
drop(write_lock.take());
}
}
impl Log for SettableLog {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
let inner = self.inner.read().unwrap();
if let Some(log) = &*inner {
log.enabled(metadata)
} else {
false
}
}
fn flush(&self) {
let inner = self.inner.read().unwrap();
if let Some(log) = &*inner {
log.flush();
}
}
fn log(&self, record: &log::Record<'_>) {
let inner = self.inner.read().unwrap();
if let Some(log) = &*inner {
log.log(record);
}
}
}
pub fn init_once() {
static INITIALIZER: Once = Once::new();
INITIALIZER.call_once(|| {
log::set_logger(&*SETTABLE_LOG).expect(
"Failed to initialize SettableLog, other log implementation already initialized?",
);
});
}
pub fn set_logger(logger: Box<dyn Log>) {
init_once();
SETTABLE_LOG.set(logger);
}
pub fn unset_logger() {
init_once();
SETTABLE_LOG.unset();
}