-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
logger.rs
82 lines (71 loc) · 2.2 KB
/
logger.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
use crate::connection::LogSettings;
use std::time::Instant;
pub(crate) struct QueryLogger<'q> {
sql: &'q str,
rows: usize,
start: Instant,
settings: LogSettings,
}
impl<'q> QueryLogger<'q> {
pub(crate) fn new(sql: &'q str, settings: LogSettings) -> Self {
Self {
sql,
rows: 0,
start: Instant::now(),
settings,
}
}
pub(crate) fn increment_rows(&mut self) {
self.rows += 1;
}
pub(crate) fn finish(&self) {
let elapsed = self.start.elapsed();
let lvl = if elapsed >= self.settings.slow_statements_duration {
self.settings.slow_statements_level
} else {
self.settings.statements_level
};
if let Some(lvl) = lvl.to_level() {
if lvl <= log::STATIC_MAX_LEVEL && lvl <= log::max_level() {
let mut summary = parse_query_summary(&self.sql);
let sql = if summary != self.sql {
summary.push_str(" …");
format!(
"\n\n{}\n",
sqlformat::format(
&self.sql,
&sqlformat::QueryParams::None,
sqlformat::FormatOptions::default()
)
)
} else {
String::new()
};
let rows = self.rows;
log::logger().log(
&log::Record::builder()
.args(format_args!(
"{}; rows: {}, elapsed: {:.3?}{}",
summary, rows, elapsed, sql
))
.level(lvl)
.module_path_static(Some("sqlx::query"))
.target("sqlx::query")
.build(),
);
}
}
}
}
impl<'q> Drop for QueryLogger<'q> {
fn drop(&mut self) {
self.finish();
}
}
fn parse_query_summary(sql: &str) -> String {
// For now, just take the first 4 words
sql.split_whitespace()
.take(4)
.collect::<Vec<&str>>()
.join(" ")
}