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
#![doc(
html_logo_url = "https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/logo-type.png",
issue_tracker_base_url = "https://github.com/tokio-rs/tracing/issues/"
)]
#![cfg_attr(docsrs, deny(rustdoc::broken_intra_doc_links))]
#[cfg(unix)]
use std::os::unix::net::UnixDatagram;
use std::{fmt, io, io::Write};
use tracing_core::{
event::Event,
field::Visit,
span::{Attributes, Id, Record},
Field, Level, Metadata, Subscriber,
};
use tracing_subscriber::{layer::Context, registry::LookupSpan};
pub struct Layer {
#[cfg(unix)]
socket: UnixDatagram,
field_prefix: Option<String>,
}
impl Layer {
pub fn new() -> io::Result<Self> {
#[cfg(unix)]
{
let socket = UnixDatagram::unbound()?;
socket.connect("/run/systemd/journal/socket")?;
Ok(Self {
socket,
field_prefix: Some("F".into()),
})
}
#[cfg(not(unix))]
Err(io::Error::new(
io::ErrorKind::NotFound,
"journald does not exist in this environment",
))
}
pub fn with_field_prefix(mut self, x: Option<String>) -> Self {
self.field_prefix = x;
self
}
}
pub fn layer() -> io::Result<Layer> {
Layer::new()
}
impl<S> tracing_subscriber::Layer<S> for Layer
where
S: Subscriber + for<'span> LookupSpan<'span>,
{
fn on_new_span(&self, attrs: &Attributes, id: &Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("unknown span");
let mut buf = Vec::with_capacity(256);
let depth = span.scope().skip(1).count();
writeln!(buf, "S{}_NAME", depth).unwrap();
put_value(&mut buf, span.name().as_bytes());
put_metadata(&mut buf, span.metadata(), Some(depth));
attrs.record(&mut SpanVisitor {
buf: &mut buf,
depth,
prefix: self.field_prefix.as_ref().map(|x| &x[..]),
});
span.extensions_mut().insert(SpanFields(buf));
}
fn on_record(&self, id: &Id, values: &Record, ctx: Context<S>) {
let span = ctx.span(id).expect("unknown span");
let depth = span.scope().skip(1).count();
let mut exts = span.extensions_mut();
let buf = &mut exts.get_mut::<SpanFields>().expect("missing fields").0;
values.record(&mut SpanVisitor {
buf,
depth,
prefix: self.field_prefix.as_ref().map(|x| &x[..]),
});
}
fn on_event(&self, event: &Event, ctx: Context<S>) {
let mut buf = Vec::with_capacity(256);
for span in ctx
.lookup_current()
.into_iter()
.flat_map(|span| span.scope().from_root())
{
let exts = span.extensions();
let fields = exts.get::<SpanFields>().expect("missing fields");
buf.extend_from_slice(&fields.0);
}
put_metadata(&mut buf, event.metadata(), None);
event.record(&mut EventVisitor::new(
&mut buf,
self.field_prefix.as_ref().map(|x| &x[..]),
));
#[cfg(unix)]
let _ = self.socket.send(&buf);
}
}
struct SpanFields(Vec<u8>);
struct SpanVisitor<'a> {
buf: &'a mut Vec<u8>,
depth: usize,
prefix: Option<&'a str>,
}
impl Visit for SpanVisitor<'_> {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
write!(self.buf, "S{}", self.depth).unwrap();
if let Some(prefix) = self.prefix {
self.buf.extend_from_slice(prefix.as_bytes());
}
self.buf.push(b'_');
put_debug(self.buf, field.name(), value);
}
}
struct EventVisitor<'a> {
buf: &'a mut Vec<u8>,
prefix: Option<&'a str>,
}
impl<'a> EventVisitor<'a> {
fn new(buf: &'a mut Vec<u8>, prefix: Option<&'a str>) -> Self {
Self { buf, prefix }
}
}
impl Visit for EventVisitor<'_> {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
if let Some(prefix) = self.prefix {
if field.name() != "message" {
self.buf.extend_from_slice(prefix.as_bytes());
self.buf.push(b'_');
}
}
put_debug(self.buf, field.name(), value);
}
}
fn put_metadata(buf: &mut Vec<u8>, meta: &Metadata, span: Option<usize>) {
if span.is_none() {
put_field(
buf,
"PRIORITY",
match *meta.level() {
Level::ERROR => b"3",
Level::WARN => b"4",
Level::INFO => b"5",
Level::DEBUG => b"6",
Level::TRACE => b"7",
},
);
}
if let Some(n) = span {
write!(buf, "S{}_", n).unwrap();
}
put_field(buf, "TARGET", meta.target().as_bytes());
if let Some(file) = meta.file() {
if let Some(n) = span {
write!(buf, "S{}_", n).unwrap();
}
put_field(buf, "CODE_FILE", file.as_bytes());
}
if let Some(line) = meta.line() {
if let Some(n) = span {
write!(buf, "S{}_", n).unwrap();
}
writeln!(buf, "CODE_LINE={}", line).unwrap();
}
}
fn put_debug(buf: &mut Vec<u8>, name: &str, value: &dyn fmt::Debug) {
sanitize_name(name, buf);
buf.push(b'\n');
buf.extend_from_slice(&[0; 8]);
let start = buf.len();
write!(buf, "{:?}", value).unwrap();
let end = buf.len();
buf[start - 8..start].copy_from_slice(&((end - start) as u64).to_le_bytes());
buf.push(b'\n');
}
fn sanitize_name(name: &str, buf: &mut Vec<u8>) {
buf.extend(
name.bytes()
.map(|c| if c == b'.' { b'_' } else { c })
.skip_while(|&c| c == b'_')
.filter(|&c| c == b'_' || char::from(c).is_ascii_alphanumeric())
.map(|c| char::from(c).to_ascii_uppercase() as u8),
);
}
fn put_field(buf: &mut Vec<u8>, name: &str, value: &[u8]) {
buf.extend_from_slice(name.as_bytes());
buf.push(b'\n');
put_value(buf, value);
}
fn put_value(buf: &mut Vec<u8>, value: &[u8]) {
buf.extend_from_slice(&(value.len() as u64).to_le_bytes());
buf.extend_from_slice(value);
buf.push(b'\n');
}