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
#![forbid(unsafe_code)]
#![deny(
missing_copy_implementations,
missing_crate_level_docs,
missing_debug_implementations,
missing_docs,
nonstandard_style,
unused_qualifications
)]
use colored::*;
use size::{Base, Size, Style};
use std::time::Instant;
use trillium::{async_trait, http_types::StatusCode, Conn, Handler, Info};
#[derive(Debug)]
struct Start(Instant);
impl Start {
pub fn now() -> Self {
Self(Instant::now())
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Logger(());
impl Logger {
pub fn new() -> Self {
Self(())
}
}
#[async_trait]
impl Handler for Logger {
async fn init(&mut self, info: &mut Info) {
log::info!(
"
🌱🦀🌱 {} started
Listening at {}{}
Control-C to quit",
info.server_description(),
info.listener_description(),
info.tcp_socket_addr()
.map(|s| format!(" (bound as tcp://{})", s))
.unwrap_or_default()
);
}
async fn run(&self, conn: Conn) -> Conn {
conn.with_state(Start::now())
}
async fn before_send(&self, mut conn: Conn) -> Conn {
if let Some(start) = conn.take_state::<Start>() {
let method = conn.method();
let status = conn.status().unwrap_or(StatusCode::NotFound);
let len = conn
.response_len()
.map(|l| {
Size::to_string(&Size::Bytes(l), Base::Base10, Style::Smart).replace(" ", "")
})
.unwrap_or_else(|| String::from("-"));
log::info!(
r#"{method} {url} {status} {response_time:?} {len}"#,
response_time = std::time::Instant::now() - start.0,
method = method,
url = conn.path(),
status = (status as u16).to_string().color(match status as u16 {
200..=299 => "green",
300..=399 => "cyan",
400..=499 => "yellow",
500..=599 => "red",
_ => "white",
}),
len = len,
);
}
conn
}
}