-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtest.rs
323 lines (276 loc) · 9.48 KB
/
test.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
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
use tempfile::tempdir;
use file_per_thread_logger::{
allow_uninitialized, initialize, initialize_with_formatter, FormatFn,
};
use log::{debug, error, info, trace, warn};
use std::collections::HashSet;
use std::env;
use std::fs;
use std::io::{self, Write};
use std::thread;
const LOG_PREFIX: &str = "my_log_test-";
/// Returns the names of the log files found in the current directory.
fn log_files(log_prefix: &str) -> io::Result<HashSet<String>> {
let current_dir = env::current_dir()?;
let mut logs = HashSet::new();
for entry in fs::read_dir(current_dir.as_path())? {
let path = entry?.path();
if let Some(filename) = path.file_name() {
let filename = filename.to_string_lossy();
if filename.starts_with(log_prefix) {
logs.insert(filename[log_prefix.len()..].to_string());
}
}
}
Ok(logs)
}
fn read_log(name: &str) -> io::Result<String> {
fs::read_to_string(format!("{}{}", LOG_PREFIX, name))
}
fn set(names: &[&str]) -> HashSet<String> {
names.iter().map(|s| s.to_string()).collect()
}
fn flush() {
log::logger().flush();
}
fn do_log(run_init: bool, formatter: Option<FormatFn>) -> thread::ThreadId {
trace!("This is a trace entry on the main thread.");
debug!("This is a debug entry on the main thread.");
info!("This is an info entry on the main thread.");
warn!("This is a warn entry on the main thread.");
error!("This is an error entry on the main thread.");
let handle = thread::spawn(move || {
if run_init {
if let Some(formatter) = formatter {
initialize_with_formatter(LOG_PREFIX, formatter);
} else {
initialize(LOG_PREFIX);
}
}
trace!("This is a trace entry from an unnamed helper thread.");
debug!("This is a debug entry from an unnamed helper thread.");
info!("This is an info entry from an unnamed helper thread.");
warn!("This is a warn entry from an unnamed helper thread.");
error!("This is an error entry from an unnamed helper thread.");
flush();
});
let unnamed_thread_id = handle.thread().id();
handle.join().unwrap();
let handle = thread::Builder::new()
.name("helper".to_string())
.spawn(move || {
if run_init {
if let Some(formatter) = formatter {
initialize_with_formatter(LOG_PREFIX, formatter);
} else {
initialize(LOG_PREFIX);
}
}
trace!("This is a trace entry from a named thread.");
debug!("This is a debug entry from a named thread.");
info!("This is an info entry from a named thread.");
warn!("This is a warn entry from a named thread.");
error!("This is an error entry from a named thread.");
flush();
})
.unwrap();
handle.join().unwrap();
flush();
unnamed_thread_id
}
#[test]
fn tests() -> io::Result<()> {
let temp_dir = tempdir()?;
env::set_current_dir(&temp_dir)?;
assert_eq!(log_files(LOG_PREFIX)?, set(&[]));
env::remove_var("RUST_LOG");
initialize(LOG_PREFIX);
// Nothing should be logged without something in the RUST_LOG env variable..
assert_eq!(log_files(LOG_PREFIX)?, set(&[]));
do_log(false, None);
assert_eq!(log_files(LOG_PREFIX)?, set(&[]));
// When the RUST_LOG variable is set, it will create the main thread file even though nothing
// has been logged yet.
env::set_var("RUST_LOG", "info");
initialize(LOG_PREFIX);
flush();
let main_log = "tests";
let named_log = "helper";
assert_eq!(log_files(LOG_PREFIX)?, set(&[main_log]));
assert_eq!(
read_log(main_log)?,
r#"INFO - Set up logging; filename prefix is my_log_test-
"#
);
let unnamed_thread_id = do_log(true, None);
let unnamed_log = format!("{:?}", unnamed_thread_id);
let unnamed_log = &unnamed_log
.chars()
.filter(|ch| ch.is_alphanumeric() || *ch == '-' || *ch == '_')
.collect::<String>();
// It then creates files for each thread with logged contents.
assert_eq!(
log_files(LOG_PREFIX)?,
set(&[main_log, named_log, unnamed_log])
);
assert_eq!(
read_log(main_log)?,
r#"INFO - Set up logging; filename prefix is my_log_test-
INFO - This is an info entry on the main thread.
WARN - This is a warn entry on the main thread.
ERROR - This is an error entry on the main thread.
"#
);
assert_eq!(
read_log(unnamed_log)?,
r#"INFO - Set up logging; filename prefix is my_log_test-
INFO - This is an info entry from an unnamed helper thread.
WARN - This is a warn entry from an unnamed helper thread.
ERROR - This is an error entry from an unnamed helper thread.
"#
);
assert_eq!(
read_log(named_log)?,
r#"INFO - Set up logging; filename prefix is my_log_test-
INFO - This is an info entry from a named thread.
WARN - This is a warn entry from a named thread.
ERROR - This is an error entry from a named thread.
"#
);
temp_dir.close()?;
Ok(())
}
#[test]
fn formatted_logs() -> io::Result<()> {
let temp_dir = tempdir()?;
env::set_current_dir(&temp_dir)?;
let formatter: FormatFn = |get_writer, record| {
let args = format!("{}", record.args());
let mut writer = get_writer.get();
writeln!(
writer,
"{} [{}:{}] {}",
record.level(),
record.file().unwrap_or_default(),
record.line().unwrap_or_default(),
args
)
};
// When the RUST_LOG variable is set, it will create the main thread file even though nothing
// has been logged yet.
env::set_var("RUST_LOG", "info");
initialize_with_formatter(LOG_PREFIX, formatter);
flush();
let main_log = "formatted_logs";
let named_log = "helper";
assert_eq!(log_files(LOG_PREFIX)?, set(&[main_log]));
assert_eq!(
read_log(main_log)?,
r#"INFO [src/lib.rs:119] Set up logging; filename prefix is my_log_test-
"#
);
let unnamed_thread_id = do_log(true, Some(formatter));
let unnamed_log = format!("{:?}", unnamed_thread_id);
let unnamed_log = &unnamed_log
.chars()
.filter(|ch| ch.is_alphanumeric() || *ch == '-' || *ch == '_')
.collect::<String>();
// It then creates files for each thread with logged contents.
assert_eq!(
log_files(LOG_PREFIX)?,
set(&[main_log, named_log, unnamed_log])
);
assert_eq!(
read_log(unnamed_log)?,
r#"INFO [src/lib.rs:119] Set up logging; filename prefix is my_log_test-
INFO [tests/test.rs:63] This is an info entry from an unnamed helper thread.
WARN [tests/test.rs:64] This is a warn entry from an unnamed helper thread.
ERROR [tests/test.rs:65] This is an error entry from an unnamed helper thread.
"#
);
assert_eq!(
read_log(named_log)?,
r#"INFO [src/lib.rs:119] Set up logging; filename prefix is my_log_test-
INFO [tests/test.rs:84] This is an info entry from a named thread.
WARN [tests/test.rs:85] This is a warn entry from a named thread.
ERROR [tests/test.rs:86] This is an error entry from a named thread.
"#
);
temp_dir.close()?;
Ok(())
}
#[test]
#[should_panic]
fn uninitialized_threads_should_panic() {
let temp_dir = tempdir().expect("Cannot create tempdir");
env::set_current_dir(&temp_dir).expect("Couldn't set current dir");
env::set_var("RUST_LOG", "info");
initialize(LOG_PREFIX);
let handle = thread::spawn(|| {
log::info!("This is a log from a thread");
});
let _ = handle.join().unwrap();
}
#[test]
fn logging_from_uninitialized_threads_allowed() -> io::Result<()> {
let temp_dir = tempdir()?;
env::set_current_dir(&temp_dir)?;
env::set_var("RUST_LOG", "info");
initialize("");
flush();
allow_uninitialized();
let handle = thread::spawn(|| {
log::info!("This is a log from a thread");
});
flush();
let unnamed_log = format!("{:?}", handle.thread().id());
let unnamed_log = &unnamed_log
.chars()
.filter(|ch| ch.is_alphanumeric() || *ch == '-' || *ch == '_')
.collect::<String>();
let _ = handle.join().unwrap();
let main_log = "logging_from_uninitialized_threads_allowed";
assert_eq!(log_files("")?, set(&[main_log, unnamed_log]));
temp_dir.close()?;
Ok(())
}
#[test]
fn log_in_log() -> io::Result<()> {
let temp_dir = tempdir()?;
env::set_current_dir(&temp_dir)?;
env::set_var("RUST_LOG", "trace");
initialize("");
flush();
struct Display;
impl std::fmt::Display for Display {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
log::info!("log 2");
Ok(())
}
}
let handle = thread::spawn(|| {
initialize("");
log::trace!("log 1");
let display = Display;
log::warn!("log 3{display}");
});
flush();
let unnamed_thread_id = handle.thread().id();
let unnamed_log = format!("{unnamed_thread_id:?}");
let unnamed_log = &unnamed_log
.chars()
.filter(|ch| ch.is_alphanumeric() || *ch == '-' || *ch == '_')
.collect::<String>();
let _ = handle.join().unwrap();
assert_eq!(log_files("")?, set(&["log_in_log", unnamed_log]));
assert_eq!(
fs::read_to_string(unnamed_log)?,
r#"INFO - Set up logging; filename prefix is
TRACE - log 1
INFO - log 2
WARN - log 3
"#
);
temp_dir.close()?;
Ok(())
}