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
use std::io::Write;
use std::thread;
use time;
use Request;
pub struct LogEntry<W> where W: Write {
line: String,
output: W,
start_time: u64,
}
impl<'a, W> LogEntry<W> where W: Write {
pub fn start(output: W, rq: &Request) -> LogEntry<W> {
LogEntry {
line: format!("{} {}", rq.method(), rq.raw_url()),
output: output,
start_time: time::precise_time_ns(),
}
}
}
impl<W> Drop for LogEntry<W> where W: Write {
fn drop(&mut self) {
write!(self.output, "{} - ", self.line).unwrap();
if thread::panicking() {
write!(self.output, " - PANIC!").unwrap();
} else {
let elapsed = time::precise_time_ns() - self.start_time;
format_time(self.output.by_ref(), elapsed);
}
writeln!(self.output, "").unwrap();
}
}
fn format_time<W>(mut out: W, time: u64) where W: Write {
if time < 1_000 {
write!(out, "{}ns", time).unwrap()
} else if time < 1_000_000 {
write!(out, "{:.1}us", time as f64 / 1_000.0).unwrap()
} else if time < 1_000_000_000 {
write!(out, "{:.1}ms", time as f64 / 1_000_000.0).unwrap()
} else {
write!(out, "{:.1}s", time as f64 / 1_000_000_000.0).unwrap()
}
}