/
sloggish_collector.rs
284 lines (258 loc) · 7.76 KB
/
sloggish_collector.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
use nu_ansi_term::{Color, Style};
use tracing::{
field::{Field, Visit},
Collect, Id, Level, Metadata,
};
use tracing_core::span::Current;
use std::{
cell::RefCell,
collections::HashMap,
fmt,
io::{self, Write},
sync::{
atomic::{AtomicUsize, Ordering},
Mutex,
},
thread,
time::SystemTime,
};
/// Tracks the currently executing span on a per-thread basis.
#[derive(Clone)]
pub struct CurrentSpanPerThread {
current: &'static thread::LocalKey<RefCell<Vec<Id>>>,
}
impl CurrentSpanPerThread {
pub fn new() -> Self {
thread_local! {
static CURRENT: RefCell<Vec<Id>> = RefCell::new(vec![]);
};
Self { current: &CURRENT }
}
/// Returns the [`Id`](::Id) of the span in which the current thread is
/// executing, or `None` if it is not inside of a span.
pub fn id(&self) -> Option<Id> {
self.current
.with(|current| current.borrow().last().cloned())
}
pub fn enter(&self, span: Id) {
self.current.with(|current| {
current.borrow_mut().push(span);
})
}
pub fn exit(&self) {
self.current.with(|current| {
let _ = current.borrow_mut().pop();
})
}
}
pub struct SloggishCollector {
// TODO: this can probably be unified with the "stack" that's used for
// printing?
current: CurrentSpanPerThread,
indent_amount: usize,
stderr: io::Stderr,
stack: Mutex<Vec<Id>>,
spans: Mutex<HashMap<Id, Span>>,
ids: AtomicUsize,
}
struct Span {
parent: Option<Id>,
kvs: Vec<(&'static str, String)>,
metadata: &'static Metadata<'static>,
}
struct Event<'a> {
stderr: io::StderrLock<'a>,
comma: bool,
}
struct ColorLevel<'a>(&'a Level);
impl<'a> fmt::Display for ColorLevel<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> 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)
}
}
impl Span {
fn new(parent: Option<Id>, attrs: &tracing::span::Attributes<'_>) -> Self {
let mut span = Self {
parent,
kvs: Vec::new(),
metadata: attrs.metadata(),
};
attrs.record(&mut span);
span
}
}
impl Visit for Span {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
self.kvs.push((field.name(), format!("{:?}", value)))
}
}
impl<'a> Visit for Event<'a> {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
write!(
&mut self.stderr,
"{comma} ",
comma = if self.comma { "," } else { "" },
)
.unwrap();
let name = field.name();
if name == "message" {
write!(
&mut self.stderr,
"{}",
// Have to alloc here due to `nu_ansi_term`'s API...
Style::new().bold().paint(format!("{:?}", value))
)
.unwrap();
} else {
write!(
&mut self.stderr,
"{}: {:?}",
Style::new().bold().paint(name),
value
)
.unwrap();
}
self.comma = true;
}
}
impl SloggishCollector {
pub fn new(indent_amount: usize) -> Self {
Self {
current: CurrentSpanPerThread::new(),
indent_amount,
stderr: io::stderr(),
stack: Mutex::new(vec![]),
spans: Mutex::new(HashMap::new()),
ids: AtomicUsize::new(1),
}
}
fn print_kvs<'a, I, K, V>(
&self,
writer: &mut impl Write,
kvs: I,
leading: &str,
) -> io::Result<()>
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<str> + 'a,
V: fmt::Display + 'a,
{
let mut kvs = kvs.into_iter();
if let Some((k, v)) = kvs.next() {
write!(
writer,
"{}{}: {}",
leading,
Style::new().bold().paint(k.as_ref()),
v
)?;
}
for (k, v) in kvs {
write!(writer, ", {}: {}", Style::new().bold().paint(k.as_ref()), v)?;
}
Ok(())
}
fn print_indent(&self, writer: &mut impl Write, indent: usize) -> io::Result<()> {
for _ in 0..(indent * self.indent_amount) {
write!(writer, " ")?;
}
Ok(())
}
}
impl Collect for SloggishCollector {
fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
true
}
fn new_span(&self, span: &tracing::span::Attributes<'_>) -> tracing::Id {
let next = self.ids.fetch_add(1, Ordering::SeqCst) as u64;
let id = tracing::Id::from_u64(next);
let span = Span::new(self.current.id(), span);
self.spans.lock().unwrap().insert(id.clone(), span);
id
}
fn record(&self, span: &tracing::Id, values: &tracing::span::Record<'_>) {
let mut spans = self.spans.lock().expect("mutex poisoned!");
if let Some(span) = spans.get_mut(span) {
values.record(span);
}
}
fn record_follows_from(&self, _span: &tracing::Id, _follows: &tracing::Id) {
// unimplemented
}
fn enter(&self, span_id: &tracing::Id) {
self.current.enter(span_id.clone());
let mut stderr = self.stderr.lock();
let mut stack = self.stack.lock().unwrap();
let spans = self.spans.lock().unwrap();
let data = spans.get(span_id);
let parent = data.and_then(|span| span.parent.as_ref());
if !stack.iter().any(|id| id == span_id) {
let indent = if let Some(idx) = stack
.iter()
.position(|id| parent.map(|p| id == p).unwrap_or(false))
{
let idx = idx + 1;
stack.truncate(idx);
idx
} else {
stack.clear();
0
};
self.print_indent(&mut stderr, indent).unwrap();
stack.push(span_id.clone());
if let Some(data) = data {
self.print_kvs(&mut stderr, data.kvs.iter().map(|(k, v)| (k, v)), "")
.unwrap();
}
writeln!(&mut stderr).unwrap();
}
}
fn event(&self, event: &tracing::Event<'_>) {
let mut stderr = self.stderr.lock();
let indent = self.stack.lock().unwrap().len();
self.print_indent(&mut stderr, indent).unwrap();
write!(
&mut stderr,
"{timestamp} {level} {target}",
timestamp = humantime::format_rfc3339_seconds(SystemTime::now()),
level = ColorLevel(event.metadata().level()),
target = &event.metadata().target(),
)
.unwrap();
let mut visitor = Event {
stderr,
comma: false,
};
event.record(&mut visitor);
writeln!(&mut visitor.stderr).unwrap();
}
#[inline]
fn exit(&self, _span: &tracing::Id) {
// TODO: unify stack with current span
self.current.exit();
}
fn try_close(&self, _id: tracing::Id) -> bool {
// TODO: GC unneeded spans.
false
}
fn current_span(&self) -> Current {
if let Some(id) = self.current.id() {
let metadata = self
.spans
.lock()
.unwrap()
.get(&id)
.unwrap_or_else(|| panic!("no metadata stored for span with ID {:?}", id))
.metadata;
return Current::new(id, metadata);
}
Current::none()
}
}