/
testlog.rs
180 lines (154 loc) · 5.22 KB
/
testlog.rs
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
// Copyright 2016 Victor Brekenfeld
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! Module providing the TestLogger Implementation
use super::logging::should_skip;
use crate::{config::TimeFormat, Config, LevelPadding, SharedLogger};
use log::{set_boxed_logger, set_max_level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use std::thread;
/// The TestLogger struct. Provides a very basic Logger implementation that may be captured by cargo.
pub struct TestLogger {
level: LevelFilter,
config: Config,
}
impl TestLogger {
/// init function. Globally initializes the TestLogger as the one and only used log facility.
///
/// Takes the desired `Level` and `Config` as arguments. They cannot be changed later on.
/// Fails if another Logger was already initialized.
///
/// # Examples
/// ```
/// # extern crate simplelog;
/// # use simplelog::*;
/// # fn main() {
/// #[cfg(not(test))]
/// // another logger
/// # let _ = TestLogger::init(LevelFilter::Info, Config::default());
/// #[cfg(test)]
/// let _ = TestLogger::init(LevelFilter::Info, Config::default());
/// # }
/// ```
pub fn init(log_level: LevelFilter, config: Config) -> Result<(), SetLoggerError> {
set_max_level(log_level);
set_boxed_logger(TestLogger::new(log_level, config))
}
/// allows to create a new logger, that can be independently used, no matter what is globally set.
///
/// no macros are provided for this case and you probably
/// dont want to use this function, but `init()`, if you dont want to build a `CombinedLogger`.
///
/// Takes the desired `Level` and `Config` as arguments. They cannot be changed later on.
///
/// # Examples
/// ```
/// # extern crate simplelog;
/// # use simplelog::*;
/// # fn main() {
/// #[cfg(not(test))]
/// // another logger
/// # let test_logger = TestLogger::new(LevelFilter::Info, Config::default());
/// #[cfg(test)]
/// let test_logger = TestLogger::new(LevelFilter::Info, Config::default());
/// # }
/// ```
pub fn new(log_level: LevelFilter, config: Config) -> Box<TestLogger> {
Box::new(TestLogger {
level: log_level,
config,
})
}
}
impl Log for TestLogger {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.level() <= self.level
}
fn log(&self, record: &Record<'_>) {
if self.enabled(record.metadata()) {
let _ = log(&self.config, record);
}
}
fn flush(&self) {}
}
impl SharedLogger for TestLogger {
fn level(&self) -> LevelFilter {
self.level
}
fn config(&self) -> Option<&Config> {
Some(&self.config)
}
fn as_log(self: Box<Self>) -> Box<dyn Log> {
Box::new(*self)
}
}
#[inline(always)]
pub fn log(config: &Config, record: &Record<'_>) {
if should_skip(&config, &record) {
return;
}
if config.time <= record.level() && config.time != LevelFilter::Off {
write_time(config);
}
if config.level <= record.level() && config.level != LevelFilter::Off {
write_level(record, config);
}
if config.thread < record.level() && config.thread != LevelFilter::Off {
write_thread_id();
}
if config.target <= record.level() && config.target != LevelFilter::Off {
write_target(record);
}
if config.location <= record.level() && config.location != LevelFilter::Off {
write_location(record);
}
write_args(record);
}
#[inline(always)]
pub fn write_time(config: &Config) {
use time::format_description::well_known::*;
let time = time::OffsetDateTime::now_utc().to_offset(config.time_offset);
let res = match config.time_format {
TimeFormat::Rfc2822 => time.format(&Rfc2822),
TimeFormat::Rfc3339 => time.format(&Rfc3339),
TimeFormat::Custom(format) => time.format(&format),
};
match res {
Ok(time) => println!("{} ", time),
Err(err) => panic!("Invalid time format: {}", err),
};
}
#[inline(always)]
pub fn write_level(record: &Record<'_>, config: &Config) {
match config.level_padding {
LevelPadding::Left => print!("[{: >5}] ", record.level()),
LevelPadding::Right => print!("[{: <5}] ", record.level()),
LevelPadding::Off => print!("[{}] ", record.level()),
};
}
#[inline(always)]
pub fn write_thread_id() {
let id = format!("{:?}", thread::current().id());
let id = id.replace("ThreadId(", "");
let id = id.replace(")", "");
print!("({}) ", id);
}
#[inline(always)]
pub fn write_target(record: &Record<'_>) {
print!("{}: ", record.target());
}
#[inline(always)]
pub fn write_location(record: &Record<'_>) {
let file = record.file().unwrap_or("<unknown>");
if let Some(line) = record.line() {
print!("[{}:{}] ", file, line);
} else {
print!("[{}:<unknown>] ", file);
}
}
#[inline(always)]
pub fn write_args(record: &Record<'_>) {
println!("{}", record.args());
}