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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#![cfg_attr(feature = "fatal-warnings", deny(warnings))]
#![deny(clippy::correctness)]
#![warn(clippy::pedantic)]
#![allow(clippy::inline_always)]
use dashmap::DashMap;
use once_cell::sync::Lazy;
use std::fmt;
use std::fs::File;
use std::io;
use std::io::Write;
use std::net::TcpStream;
use std::str::FromStr;
static DIRTY_FILES: Lazy<DashMap<&str, File>> = Lazy::new(DashMap::new);
static DIRTY_TCP: Lazy<DashMap<(&str, u16), TcpStream>> = Lazy::new(DashMap::new);
#[macro_export]
macro_rules! ddbg {
($uri:expr, $f:literal) => {{
$crate::dirty_log_message(
$uri,
::std::format_args!(::std::concat!("[{}:{}] ", $f), ::std::file!(), ::std::line!()),
);
}};
($uri:expr, $f:literal, $($arg:tt)*) => {{
$crate::dirty_log_message(
$uri,
::std::format_args!(::std::concat!("[{}:{}] ", $f), ::std::file!(), ::std::line!(), $($arg)*),
);
}};
}
#[inline(always)]
fn dirty_log_str_writer(writer: &mut impl Write, args: fmt::Arguments<'_>) -> io::Result<()> {
writer.write_fmt(args)?;
writer.write_all("\n".as_bytes())?;
writer.flush()
}
#[inline(always)]
fn dirty_log_str_file(filepath: &'static str, args: fmt::Arguments<'_>) -> io::Result<()> {
let mut entry = DIRTY_FILES.entry(filepath).or_try_insert_with(move || {
let file = File::options().create(true).append(true).open(filepath)?;
Ok::<_, io::Error>(file)
})?;
let file = entry.value_mut();
dirty_log_str_writer(file, args)
}
#[inline(always)]
fn dirty_log_str_tcp(
hostname: &'static str,
port: u16,
args: fmt::Arguments<'_>,
) -> io::Result<()> {
let mut entry = DIRTY_TCP.entry((hostname, port)).or_try_insert_with(move || {
let stream = TcpStream::connect((hostname, port))?;
Ok::<_, io::Error>(stream)
})?;
let stream = entry.value_mut();
dirty_log_str_writer(stream, args)
}
#[doc(hidden)]
pub fn dirty_log_message(uri: &'static str, args: fmt::Arguments<'_>) {
let result = if let Some(authority) = uri.strip_prefix("tcp://") {
let (hostname, port) = authority.rsplit_once(':').expect("invalid tcp uri");
let hostname =
hostname.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(hostname);
let port = u16::from_str(port).expect("invalid port number");
dirty_log_str_tcp(hostname, port, args)
} else {
let filepath = uri.strip_prefix("file://").unwrap_or(uri);
dirty_log_str_file(filepath, args)
};
if let Err(e) = result {
panic!("failed to log to \"{}\": {}", uri, e);
}
}
#[cfg(test)]
mod test {
use indoc::indoc;
use std::collections::HashSet;
use std::io::Read;
use std::net::TcpStream;
use std::thread::JoinHandle;
struct TempFilepath {
filepath: String,
}
impl TempFilepath {
fn new() -> TempFilepath {
use rand::distributions::Alphanumeric;
use rand::thread_rng;
use rand::Rng;
let dir = std::env::temp_dir();
let filename: String =
thread_rng().sample_iter(&Alphanumeric).take(30).map(char::from).collect();
let filepath = dir.join(format!("dirty_debug_test_{}", filename)).display().to_string();
TempFilepath { filepath }
}
fn read(&self) -> String {
std::fs::read_to_string(&self.filepath).unwrap()
}
}
impl Drop for TempFilepath {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.filepath);
}
}
struct Listener {
thread_handler: JoinHandle<String>,
port: u16,
}
impl Listener {
fn new() -> Listener {
Listener::new_with_bind("127.0.0.1")
}
fn new_with_bind(bind: &str) -> Listener {
use std::net::TcpListener;
use std::thread::spawn;
let listener: TcpListener =
TcpListener::bind(format!("{}:0", bind)).expect("fail to bind");
let port: u16 = listener.local_addr().unwrap().port();
let thread_handler = spawn(move || {
let mut content: String = String::with_capacity(1024);
let mut stream: TcpStream = listener.incoming().next().unwrap().unwrap();
while !content.contains("==EOF==") {
let mut buffer: [u8; 8] = [0; 8];
let read = stream.read(&mut buffer).unwrap();
let s = std::str::from_utf8(&buffer[0..read]).unwrap();
content.push_str(s);
}
content
});
Listener { thread_handler, port }
}
fn content(self) -> String {
self.thread_handler.join().unwrap()
}
}
macro_rules! make_static {
($str:expr) => {{
static CELL: ::once_cell::sync::OnceCell<String> = ::once_cell::sync::OnceCell::new();
CELL.set($str.to_owned()).unwrap();
CELL.get().unwrap().as_str()
}};
}
fn read_log_strip_source_info(log: String) -> String {
let mut stripped_log = String::with_capacity(log.len());
for line in log.lines() {
let stripped = match line.starts_with('[') {
true => line.splitn(2, " ").skip(1).next().unwrap_or(""),
false => line,
};
stripped_log.push_str(stripped);
stripped_log.push('\n');
}
stripped_log
}
fn assert_log(log: String, expected: &str) {
let stripped_log = read_log_strip_source_info(log);
assert_eq!(stripped_log, expected);
}
#[test]
fn test_ddbg_file_and_line_number() {
let temp_file: TempFilepath = TempFilepath::new();
let filepath: &'static str = make_static!(temp_file.filepath);
ddbg!(filepath, "test");
let line = line!() - 1;
assert_eq!(temp_file.read(), format!("[{}:{}] test\n", file!(), line));
}
#[test]
fn test_ddbg_simple() {
let temp_file: TempFilepath = TempFilepath::new();
let filepath: &'static str = make_static!(temp_file.filepath);
ddbg!(filepath, "numbers={:?}", [1, 2, 3]);
assert_log(temp_file.read(), "numbers=[1, 2, 3]\n");
}
#[test]
fn test_ddbg_multiple_syntaxes() {
let temp_file: TempFilepath = TempFilepath::new();
let filepath: &'static str = make_static!(temp_file.filepath);
ddbg!(filepath, "nothing to format");
ddbg!(filepath, "another nothing to format",);
ddbg!(filepath, "");
ddbg!(filepath, "a {} b {}", 23, "foo");
ddbg!(filepath, "a {} b {}", 32, "bar",);
let expected = indoc! { r#"
nothing to format
another nothing to format
a 23 b foo
a 32 b bar
"#
};
assert_log(temp_file.read(), expected);
}
#[test]
fn test_ddbg_file_append() {
let temp_file: TempFilepath = TempFilepath::new();
let filepath: &'static str = make_static!(temp_file.filepath);
std::fs::write(filepath, "[file.rs:23] first\n").unwrap();
ddbg!(filepath, "second");
let expected = indoc! { r#"
first
second
"#
};
assert_log(temp_file.read(), expected);
}
#[test]
fn test_ddbg_multiline() {
let temp_file: TempFilepath = TempFilepath::new();
let filepath: &'static str = make_static!(temp_file.filepath);
ddbg!(filepath, "This log\nmessage\nspans multiple lines!");
let expected = indoc! { r#"
This log
message
spans multiple lines!
"#
};
assert_log(temp_file.read(), expected);
}
#[test]
fn test_ddbg_uri_scheme_file() {
let temp_file: TempFilepath = TempFilepath::new();
let filepath: &'static str = make_static!(format!("file://{}", temp_file.filepath));
ddbg!(filepath, "test!");
assert_log(temp_file.read(), "test!\n");
}
#[test]
fn test_ddbg_multithread_no_corrupted_lines() {
use std::str::FromStr;
use std::thread::{spawn, JoinHandle};
const THREAD_NUM: usize = 20;
const ITERATIONS: usize = 1000;
const REPETITIONS: usize = 1000;
let temp_file: TempFilepath = TempFilepath::new();
let filepath: &'static str = make_static!(temp_file.filepath);
let mut threads: Vec<JoinHandle<()>> = Vec::with_capacity(THREAD_NUM);
for i in 0..THREAD_NUM {
let thread = spawn(move || {
for j in 0..ITERATIONS {
ddbg!(filepath, "{}", format!("{}:{}_", i, j).repeat(REPETITIONS));
}
});
threads.push(thread);
}
for thread in threads {
thread.join().unwrap();
}
let mut lines_added: HashSet<(u16, u16)> = HashSet::with_capacity(THREAD_NUM * ITERATIONS);
for i in 0..THREAD_NUM {
for j in 0..ITERATIONS {
lines_added.insert((i as u16, j as u16));
}
}
let log = read_log_strip_source_info(temp_file.read());
for line in log.lines() {
let token = line.splitn(2, "_").next().unwrap();
let mut iter = token.split(":");
let i = u16::from_str(iter.next().unwrap()).unwrap();
let j = u16::from_str(iter.next().unwrap()).unwrap();
let expected = format!("{}:{}_", i, j).repeat(REPETITIONS);
assert_eq!(line, expected);
lines_added.remove(&(i, j));
}
assert!(lines_added.is_empty());
}
#[test]
fn test_ddbg_uri_scheme_tcp_hostname() {
let tcp_listener: Listener = Listener::new();
let uri: &'static str = make_static!(format!("tcp://localhost:{}", tcp_listener.port));
ddbg!(uri, "test hostname!");
ddbg!(uri, "==EOF==");
assert_log(tcp_listener.content(), "test hostname!\n==EOF==\n");
}
#[test]
fn test_ddbg_uri_scheme_tcp_ipv4() {
let tcp_listener: Listener = Listener::new();
let uri: &'static str = make_static!(format!("tcp://127.0.0.1:{}", tcp_listener.port));
ddbg!(uri, "test ipv4!");
ddbg!(uri, "==EOF==");
assert_log(tcp_listener.content(), "test ipv4!\n==EOF==\n");
}
#[test]
fn test_ddbg_uri_scheme_tcp_ipv6() {
let tcp_listener: Listener = Listener::new_with_bind("::1");
let uri: &'static str = make_static!(format!("tcp://[::1]:{}", tcp_listener.port));
ddbg!(uri, "test ipv6!");
ddbg!(uri, "==EOF==");
assert_log(tcp_listener.content(), "test ipv6!\n==EOF==\n");
}
}