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
use std::{env, fmt, io};
use ansi_term::{Color, Style};
use anyhow::anyhow;
use datasize::DataSize;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use tracing::{
field::{Field, Visit},
Event, Level, Subscriber,
};
use tracing_subscriber::{
fmt::{
format,
time::{FormatTime, SystemTime},
FmtContext, FormatEvent, FormatFields, FormattedFields,
},
registry::LookupSpan,
EnvFilter,
};
const LOG_CONFIGURATION_ENVVAR: &str = "RUST_LOG";
const LOG_FIELD_MESSAGE: &str = "message";
const LOG_FIELD_TARGET: &str = "log.target";
const LOG_FIELD_MODULE: &str = "log.module_path";
const LOG_FIELD_FILE: &str = "log.file";
const LOG_FIELD_LINE: &str = "log.line";
#[derive(DataSize, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct LoggingConfig {
format: LoggingFormat,
color: bool,
abbreviate_modules: bool,
}
impl LoggingConfig {
pub fn new(format: LoggingFormat, color: bool, abbreviate_modules: bool) -> Self {
LoggingConfig {
format,
color,
abbreviate_modules,
}
}
}
#[derive(DataSize, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum LoggingFormat {
Text,
Json,
}
impl Default for LoggingFormat {
fn default() -> Self {
LoggingFormat::Text
}
}
struct FmtEvent {
ansi_color: bool,
abbreviate_modules: bool,
}
impl FmtEvent {
fn new(ansi_color: bool, abbreviate_modules: bool) -> Self {
FmtEvent {
ansi_color,
abbreviate_modules,
}
}
fn enable_dimmed_if_ansi(&self, writer: &mut dyn fmt::Write) -> fmt::Result {
if self.ansi_color {
write!(writer, "{}", Style::new().dimmed().prefix())
} else {
Ok(())
}
}
fn disable_dimmed_if_ansi(&self, writer: &mut dyn fmt::Write) -> fmt::Result {
if self.ansi_color {
write!(writer, "{}", Style::new().dimmed().suffix())
} else {
Ok(())
}
}
}
#[derive(Default)]
struct FieldVisitor {
module: Option<String>,
file: Option<String>,
line: Option<u32>,
}
impl Visit for FieldVisitor {
fn record_str(&mut self, field: &Field, value: &str) {
if field.name() == LOG_FIELD_MODULE {
self.module = Some(value.to_string())
} else if field.name() == LOG_FIELD_FILE {
self.file = Some(value.to_string())
}
}
fn record_u64(&mut self, field: &Field, value: u64) {
if field.name() == LOG_FIELD_LINE {
self.line = Some(value as u32)
}
}
fn record_debug(&mut self, _field: &Field, _value: &dyn fmt::Debug) {}
}
impl<S, N> FormatEvent<S, N> for FmtEvent
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
writer: &mut dyn fmt::Write,
event: &Event<'_>,
) -> fmt::Result {
self.enable_dimmed_if_ansi(writer)?;
SystemTime.format_time(writer)?;
self.disable_dimmed_if_ansi(writer)?;
let meta = event.metadata();
if self.ansi_color {
let color = match *meta.level() {
Level::TRACE => Color::Purple,
Level::DEBUG => Color::Blue,
Level::INFO => Color::Green,
Level::WARN => Color::Yellow,
Level::ERROR => Color::Red,
};
write!(
writer,
" {}{:<6}{}",
color.prefix(),
meta.level().to_string(),
color.suffix()
)?;
} else {
write!(writer, " {:<6}", meta.level().to_string())?;
}
let mut span_seen = false;
ctx.visit_spans(|span| {
write!(writer, "{}", span.metadata().name())?;
span_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!(writer, "{{{}}}", fields)?;
}
writer.write_char(':')
})?;
if span_seen {
writer.write_char(' ')?;
}
let mut field_visitor = FieldVisitor::default();
event.record(&mut field_visitor);
let module = {
let full_module_path = meta
.module_path()
.or_else(|| field_visitor.module.as_deref())
.unwrap_or_default();
if self.abbreviate_modules {
let mut parts: SmallVec<[&str; 6]> = full_module_path.split("::").collect();
let count = parts.len();
if count > 1 {
for part in parts.iter_mut().take(count - 1) {
assert!(part.is_ascii());
*part = &part[0..1];
}
}
parts.join(":")
} else {
full_module_path.to_owned()
}
};
let file = if !self.abbreviate_modules {
meta.file()
.or_else(|| field_visitor.file.as_deref())
.unwrap_or_default()
.rsplitn(2, '/')
.next()
.unwrap_or_default()
} else {
""
};
let line = meta.line().or(field_visitor.line).unwrap_or_default();
if !module.is_empty() && (!file.is_empty() || self.abbreviate_modules) {
self.enable_dimmed_if_ansi(writer)?;
write!(writer, "[{} {}:{}] ", module, file, line,)?;
self.disable_dimmed_if_ansi(writer)?;
}
ctx.format_fields(writer, event)?;
writeln!(writer)
}
}
pub fn init() -> anyhow::Result<()> {
init_with_config(&Default::default())
}
pub fn init_with_config(config: &LoggingConfig) -> anyhow::Result<()> {
let formatter = format::debug_fn(|writer, field, value| match field.name() {
LOG_FIELD_MESSAGE => write!(writer, "{:?}", value),
LOG_FIELD_TARGET | LOG_FIELD_MODULE | LOG_FIELD_FILE | LOG_FIELD_LINE => Ok(()),
_ => write!(writer, "; {}={:?}", field, value),
});
let filter = EnvFilter::new(
env::var(LOG_CONFIGURATION_ENVVAR)
.as_deref()
.unwrap_or("warn,casper_node=info"),
);
match config.format {
LoggingFormat::Text => tracing_subscriber::fmt()
.with_writer(io::stdout)
.with_env_filter(filter)
.fmt_fields(formatter)
.event_format(FmtEvent::new(config.color, config.abbreviate_modules))
.try_init(),
LoggingFormat::Json => tracing_subscriber::fmt()
.with_writer(io::stdout)
.with_env_filter(filter)
.json()
.try_init(),
}
.map_err(|error| anyhow!(error))
}