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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
extern crate log;
extern crate time;
#[macro_use]
extern crate lazy_static;
use log::{Log, LogLevel, LogMetadata, LogRecord, SetLoggerError};
use std::cell::RefCell;
use std::fmt::Write;
use std::sync::{Mutex, Once, ONCE_INIT};
#[macro_export]
macro_rules! todox {
(target: $target:expr, $($arg:tt)*) => (
debug!(target: $target, $($arg)*);
);
($($arg:tt)*) => (
debug!($($arg)*);
)
}
#[macro_export]
macro_rules! note {
($is_error:expr, target: $target:expr, $($arg:tt)*) => (
log!(target: $target,
if $is_error { log::LogLevel::Error } else { log::LogLevel::Warn },
$($arg)*);
);
($is_error:expr, $($arg:tt)*) => (
log!(if $is_error { log::LogLevel::Error } else { log::LogLevel::Warn },
$($arg)*);
)
}
pub struct Loggy {
pub prefix: &'static str,
pub show_time: bool,
pub log_level: LogLevel,
}
impl Log for Loggy {
fn enabled(&self, metadata: &LogMetadata) -> bool {
metadata.level() == LogLevel::Debug || metadata.level() <= self.log_level
}
fn log(&self, record: &LogRecord) {
count_errors(record.level());
if self.enabled(record.metadata()) {
emit_message(record.level(), self.format_message(record).as_ref());
}
}
}
lazy_static!(static ref TOTAL_THREADS: Mutex<RefCell<usize>> = Mutex::new(RefCell::new(0)););
thread_local!(static THREAD_ID: RefCell<Option<usize>> = RefCell::new(None););
impl Loggy {
fn format_message(&self, record: &LogRecord) -> String {
let mut message = String::with_capacity(256);
message.push_str(self.prefix);
THREAD_ID.with(|thread_id_cell| {
let mut current_thread_option = thread_id_cell.borrow_mut();
if current_thread_option.is_none() {
let lock_total_threads = TOTAL_THREADS.lock().unwrap();
let mut total_threads = lock_total_threads.borrow_mut();
*current_thread_option = Some(*total_threads);
*total_threads += 1;
}
let current_thread_id = current_thread_option.unwrap();
if current_thread_id > 0 {
write!(&mut message, "[{}]", current_thread_id).unwrap();
}
});
message.push(':');
if self.show_time {
message.push(' ');
message.push_str(
time::strftime("%Y-%m-%d %H:%M:%S", &time::now())
.unwrap()
.as_ref(),
);
}
write!(&mut message, " [{}]", record.level().to_string()).unwrap();
if record.level() == LogLevel::Debug {
write!(
&mut message,
" {}:{}:",
record.location().file(),
record.location().line()
).unwrap();
} else {
write!(&mut message, " {}:", record.location().module_path()).unwrap();
}
write!(&mut message, " {}\n", record.args()).unwrap();
message
}
}
lazy_static!(static ref TOTAL_ERRORS: Mutex<RefCell<usize>> = Mutex::new(RefCell::new(0)););
thread_local!(static THREAD_ERRORS: RefCell<usize> = RefCell::new(0););
fn count_errors(level: LogLevel) {
if level == LogLevel::Error {
let lock_errors = TOTAL_ERRORS.lock().unwrap();
*lock_errors.borrow_mut() += 1;
THREAD_ERRORS.with(|thread_errors_cell| {
*thread_errors_cell.borrow_mut() += 1;
});
}
}
enum LogSink {
Stderr,
Buffer,
}
lazy_static!(static ref LOG_BUFFER: Mutex<RefCell<Option<String>>> =
Mutex::new(RefCell::new(None)););
fn set_log_sink(log_sink: LogSink) {
let lock_log_buffer = LOG_BUFFER.lock().unwrap();
match log_sink {
LogSink::Stderr => {
*lock_log_buffer.borrow_mut() = None;
}
LogSink::Buffer => {
*lock_log_buffer.borrow_mut() = Some(String::new());
}
};
}
pub fn assert_log(expected: &str) {
let lock_log_buffer = LOG_BUFFER.lock().unwrap();
let mut log_buffer = lock_log_buffer.borrow_mut();
match *log_buffer {
None => {
panic!("asserting log when logging to stderr");
}
Some(ref mut actual) => {
if actual != expected {
print!(
"ACTUAL LOG:\n{}\nIS DIFFERENT FROM EXPECTED LOG:\n{}\n",
actual,
expected
);
assert_eq!("ACTUAL LOG", "EXPECTED LOG");
}
actual.clear();
}
}
}
pub fn clear_log() {
let lock_log_buffer = LOG_BUFFER.lock().unwrap();
let mut log_buffer = lock_log_buffer.borrow_mut();
match *log_buffer {
None => {
panic!("clearing log when logging to stderr");
}
Some(ref mut actual) => {
actual.clear();
}
}
}
lazy_static!(static ref MIRROR_TO_STDERR: bool =
std::env::var("LOGGY_MIRROR_TO_STDERR").map(|var| var != "").unwrap_or(false););
fn emit_message(log_level: LogLevel, message: &str) {
if log_level == LogLevel::Debug {
eprint!("{}", message);
return;
}
let lock_log_buffer = LOG_BUFFER.lock().unwrap();
let mut log_buffer = lock_log_buffer.borrow_mut();
match *log_buffer {
None => {
eprint!("{}", message);
}
Some(ref mut buffer) => {
if *MIRROR_TO_STDERR {
eprint!("{}", message);
}
buffer.push_str(message.as_ref());
}
}
}
pub fn init(loggy: Loggy) -> Result<(), SetLoggerError> {
log::set_logger(|max_log_level| {
max_log_level.set(
if cfg!(debug_assertions) {
LogLevel::Debug
} else {
loggy.log_level
}.to_log_level_filter(),
);
return Box::new(loggy);
})
}
static LOGGER_INIT: Once = ONCE_INIT;
#[macro_export]
macro_rules! test_loggy {
($(#[$attr:meta])*, $name:ident, $test:block) => {
#[test]
$( #[$attr] )*
fn $name() {
loggy::before_test(false);
$test
loggy::after_test();
}
};
($name:ident, $test:block) => {
#[test]
fn $name() {
loggy::before_test();
$test
loggy::after_test();
}
};
}
#[doc(hidden)]
pub fn before_test() {
LOGGER_INIT.call_once(|| {
init(Loggy {
prefix: "test",
show_time: false,
log_level: LogLevel::Info,
}).unwrap()
});
let lock_total_threads = TOTAL_THREADS.lock().unwrap();
*lock_total_threads.borrow_mut() = 0;
let lock_errors = TOTAL_ERRORS.lock().unwrap();
*lock_errors.borrow_mut() = 0;
THREAD_ID.with(|thread_id_cell| { *thread_id_cell.borrow_mut() = None; });
THREAD_ERRORS.with(|thread_errors_cell| {
*thread_errors_cell.borrow_mut() = 0;
});
set_log_sink(LogSink::Buffer);
}
#[doc(hidden)]
pub fn after_test() {
assert_log("");
set_log_sink(LogSink::Stderr);
}
pub struct ErrorsScope {
errors: usize,
}
impl ErrorsScope {
pub fn new() -> ErrorsScope {
THREAD_ERRORS.with(|thread_errors_cell| {
ErrorsScope { errors: *thread_errors_cell.borrow() }
})
}
pub fn errors(&self) -> usize {
THREAD_ERRORS.with(|thread_errors_cell| {
*thread_errors_cell.borrow() - self.errors
})
}
pub fn had_errors(&self) -> bool {
self.errors() > 0
}
}
pub fn errors() -> usize {
let lock_errors = TOTAL_ERRORS.lock().unwrap();
let errors = *lock_errors.borrow();
errors
}
pub fn had_errors() -> bool {
errors() > 0
}