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
#[macro_use]
extern crate log;
extern crate env_logger;
use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::io::{self, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use env_logger::filter::{Builder, Filter};
use log::{LevelFilter, Metadata, Record};
thread_local! {
static WRITER: RefCell<Option<io::BufWriter<File>>> = RefCell::new(None);
}
static ALLOW_UNINITIALIZED: AtomicBool = AtomicBool::new(false);
pub type FormatFn = fn(&mut io::BufWriter<File>, &Record) -> io::Result<()>;
pub fn initialize(filename_prefix: &str) {
init_logging(filename_prefix, None)
}
pub fn initialize_with_formatter(filename_prefix: &str, formatter: FormatFn) {
init_logging(filename_prefix, Some(formatter))
}
pub fn allow_uninitialized() {
ALLOW_UNINITIALIZED.store(true, Ordering::Relaxed);
}
fn init_logging(filename_prefix: &str, formatter: Option<FormatFn>) {
let env_var = env::var_os("RUST_LOG");
if env_var.is_none() {
return;
}
let level_filter = {
let mut builder = Builder::new();
builder.parse(env_var.unwrap().to_str().unwrap());
builder.build()
};
WRITER.with(|rc| {
if rc.borrow().is_none() {
rc.replace(Some(open_file(filename_prefix)));
}
});
let logger = FilePerThreadLogger::new(level_filter, formatter);
let _ =
log::set_boxed_logger(Box::new(logger)).map(|()| log::set_max_level(LevelFilter::max()));
info!("Set up logging; filename prefix is {}", filename_prefix);
}
struct FilePerThreadLogger {
filter: Filter,
formatter: Option<FormatFn>,
}
impl FilePerThreadLogger {
pub fn new(filter: Filter, formatter: Option<FormatFn>) -> Self {
FilePerThreadLogger { filter, formatter }
}
}
impl log::Log for FilePerThreadLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
self.filter.enabled(metadata)
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
WRITER.with(|rc| {
if rc.borrow().is_none() && ALLOW_UNINITIALIZED.load(Ordering::Relaxed) {
rc.replace(Some(open_file("")));
}
let mut opt_writer = rc.borrow_mut();
let writer = opt_writer
.as_mut()
.expect("call the logger's initialize() function first");
if let Some(format_fn) = &self.formatter {
let _ = format_fn(&mut *writer, record);
} else {
let _ = writeln!(*writer, "{} - {}", record.level(), record.args());
}
})
}
}
fn flush(&self) {
WRITER.with(|rc| {
let mut opt_writer = rc.borrow_mut();
let writer = opt_writer
.as_mut()
.expect("call the logger's initialize() function first");
let _ = writer.flush();
});
}
}
fn open_file(filename_prefix: &str) -> io::BufWriter<File> {
let curthread = thread::current();
let tmpstr;
let mut path = filename_prefix.to_owned();
path.extend(
match curthread.name() {
Some(name) => name.chars(),
None => {
tmpstr = format!("{:?}", curthread.id());
tmpstr.chars()
}
}
.filter(|ch| ch.is_alphanumeric() || *ch == '-' || *ch == '_'),
);
let file = File::create(path).expect("Can't open tracing file");
io::BufWriter::new(file)
}