-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.rs
311 lines (280 loc) · 9.76 KB
/
util.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
//! Convenience functions for usage
use once_cell::sync::Lazy;
use tracing_subscriber::{
fmt::{self, format::Writer, FmtContext, FormatEvent, FormatFields},
registry::LookupSpan,
};
use tracing_log::NormalizeEvent;
use ansi_term::{Color, Style};
use anyhow::Context;
use fmt::{time::FormatTime, FormattedFields};
use std::{borrow::Cow, fmt::Write};
use tracing::{
field::{Field, Visit},
Level, Subscriber,
};
pub mod built_info {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
pub static LONG_VERSION: Lazy<String> = Lazy::new(|| {
let version = if let Some(hash) = built_info::GIT_COMMIT_HASH {
if let Some(true) = built_info::GIT_DIRTY {
format!(
"{} ({}*)",
built_info::PKG_VERSION,
&hash.get(..8).unwrap_or(hash)
)
} else {
format!(
"{} ({})",
built_info::PKG_VERSION,
&hash.get(..8).unwrap_or(hash)
)
}
} else {
built_info::PKG_VERSION.to_string()
};
format!(
"{version}\nbuilt with {}\nbuild timestamp: {}",
built_info::RUSTC_VERSION,
built_info::BUILT_TIME_UTC
)
});
struct ColorLevel<'a>(&'a Level);
impl<'a> core::fmt::Display for ColorLevel<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match *self.0 {
Level::TRACE => Color::Purple.paint("TRACE"),
Level::DEBUG => Color::Blue.paint("DEBUG"),
Level::INFO => Color::Green.paint("INFO "),
Level::WARN => Color::Yellow.paint("WARN "),
Level::ERROR => Color::Red.paint("ERROR"),
}
.fmt(f)
}
}
struct FullCtx<'a, S, N>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
N: for<'writer> FormatFields<'writer> + 'static, {
ctx: &'a FmtContext<'a, S, N>,
span: Option<&'a tracing::span::Id>,
}
impl<'a, S, N: 'a> FullCtx<'a, S, N>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
N: for<'writer> FormatFields<'writer> + 'static,
{
pub(crate) fn new(ctx: &'a FmtContext<'a, S, N>, span: Option<&'a tracing::span::Id>) -> Self {
Self { ctx, span }
}
fn bold(&self) -> Style { Style::new().bold() }
}
// TODO: This should maybe be a FormatFields instead?
struct EventFieldVisitor {
message: String,
message_visited: MessageState,
}
#[derive(Debug, PartialEq, Eq)]
enum MessageState {
/// We just saw the message, so pass a "-"
JustVisited,
/// We haven't seen the message, so just format like usual.
NotSeen,
/// We have seen the message, but we've already added the "-"
Processed,
}
impl EventFieldVisitor {
fn record_message(&mut self, value: String) {
if self.message.is_empty() {
self.message = value;
self.message_visited = MessageState::JustVisited;
} else {
let m = self.message.clone();
self.message = format!("{} - {}", value, m);
self.message_visited = MessageState::Processed;
}
}
}
impl Visit for EventFieldVisitor {
fn record_debug(&mut self, field: &Field, value: &dyn core::fmt::Debug) {
if field.name() == "message" {
self.record_message(format!("{:?}", value));
return;
}
let s = &mut self.message;
if !s.is_empty() {
// message
if self.message_visited == MessageState::JustVisited {
let _ = write!(s, " - ");
self.message_visited = MessageState::Processed;
} else {
let _ = write!(s, ", ");
}
}
let _ = write!(
s,
"{pre}{field}{pre}: {value:?}{suf}",
pre = Color::RGB(128, 128, 128).dimmed().prefix(),
suf = Color::RGB(128, 128, 128).dimmed().suffix(),
field = Style::new().underline().paint(field.name()),
value = value,
);
}
fn record_u64(&mut self, field: &Field, value: u64) {
if field.name() != "log.line" {
self.record_debug(field, &value)
}
}
fn record_str(&mut self, field: &Field, value: &str) {
// The `Visit` API erases the string slice's lifetime. However, we
// know it is part of the `Event` struct with a lifetime of `'a`. If
// (and only if!) this `LogVisitor` was constructed with the same
// lifetime parameter `'a` as the event in question, it's safe to
// cast these string slices to the `'a` lifetime.
match field.name() {
"message" => self.record_message(value.to_string()),
"log.target" | "log.module_path" | "log.file" | "log.line" => {}
_ => self.record_debug(field, &value),
}
}
}
const MARKDOWN_TOKENS: &[char] = &['_', '*', '`', '~', '#', '+', '-'];
pub trait Sanitize {
fn sanitize(&self) -> Cow<'_, str>;
}
impl<T> Sanitize for T
where T: AsRef<str>
{
fn sanitize(&self) -> Cow<'_, str> {
let this = self.as_ref();
if this.contains(MARKDOWN_TOKENS) {
let mut string = this.to_string();
for token in MARKDOWN_TOKENS {
string = string.replace(*token, &format!("\\{}", token));
}
Cow::Owned(string)
} else {
Cow::Borrowed(this)
}
}
}
impl<'a, S, N> core::fmt::Display for FullCtx<'a, S, N>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
N: for<'writer> FormatFields<'writer> + 'static,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let bold = self.bold();
let mut seen = false;
let span = self
.span
.and_then(|id| self.ctx.span(id))
.or_else(|| self.ctx.lookup_current());
#[allow(deprecated)]
let scope = span.into_iter().flat_map(|span| span.scope().from_root());
for span in scope {
write!(f, "{}", bold.paint(span.metadata().name()))?;
seen = true;
let ext = span.extensions();
let fields = &ext
.get::<FormattedFields<N>>()
.expect("Unable to find FormattedFields in extensions; this is a bug");
if !fields.is_empty() {
write!(f, "{}{}{}", bold.paint("{"), fields, bold.paint("}"))?;
}
f.write_char(':')?;
}
if seen {
f.write_char(' ')?;
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq)]
struct Formatter;
impl<S, N> FormatEvent<S, N> for Formatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
mut writer: Writer,
event: &tracing::Event<'_>,
) -> core::fmt::Result {
// Aug 27 13:18:21.944 DEBG Getting broadcaster status, channel_id:
tracing_subscriber::fmt::time::SystemTime.format_time(&mut writer)?;
write!(
writer,
" {} {} ",
ColorLevel(event.metadata().level()),
Color::Black.paint("|:")
)?;
let normalized_meta = event.normalized_metadata();
let event_meta = normalized_meta.as_ref().unwrap_or_else(|| event.metadata());
write!(writer, "{}", Color::Fixed(8).prefix())?;
if std::path::Path::new(event_meta.file().unwrap_or("/")).is_relative() {
write!(
writer,
"{}:{} ",
event_meta.file().unwrap_or("<unknown>"),
event_meta
.line()
.map(|n| n.to_string())
.unwrap_or_else(|| String::from("?"))
)?;
}
write!(writer, "{} ", event_meta.target())?;
write!(writer, "{}", Color::Fixed(8).suffix())?;
write!(writer, "{} ", Color::Fixed(250).paint("|:"))?;
let full_ctx = FullCtx::new(ctx, event.parent());
write!(writer, "{}\n└─\t", full_ctx)?;
let mut fields = EventFieldVisitor {
message: String::new(),
message_visited: MessageState::NotSeen,
};
event.record(&mut fields);
write!(writer, "{}", fields.message)?;
//ctx.format_fields(writer, event)?;
writeln!(writer)
}
}
impl<S: Subscriber + for<'a> LookupSpan<'a>> tracing_subscriber::Layer<S> for Formatter {}
/// Build a logger that does file and term logging.
pub fn build_logger() -> Result<(), anyhow::Error> {
use tracing_subscriber::prelude::__tracing_subscriber_field_MakeExt as _;
tracing_log::log_tracer::Builder::new()
.init()
.context("when building tracing builder")?;
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"))
.add_directive("hyper=off".parse()?)
.add_directive("sqlx=warn".parse()?)
.add_directive("want=info".parse()?)
.add_directive("async_tungstenite=info".parse()?)
.add_directive("tungstenite=info".parse()?)
.add_directive("reqwest=info".parse()?)
.add_directive("mio=off".parse()?);
let field_formatter = tracing_subscriber::fmt::format::debug_fn(|writer, field, value| {
write!(
writer,
"{}: {:?}",
Color::Yellow.dimmed().paint(field.name()),
value
)
})
// Use the `tracing_subscriber::MakeFmtExt` trait to wrap the
// formatter so that a delimiter is added between fields.
.delimited(", ");
let subscriber = tracing_subscriber::fmt::fmt()
.with_target(true)
.with_env_filter(filter)
.event_format(Formatter)
.fmt_fields(field_formatter)
.finish();
tracing::subscriber::set_global_default(subscriber)
.context("could not set global tracing logger")?;
Ok(())
}