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
use crate::storage_layer::JsonStorage;
use serde::ser::{SerializeMap, Serializer};
use serde_json::Value;
use std::fmt;
use std::io::Write;
use tracing::{Event, Id, Subscriber};
use tracing_core::metadata::Level;
use tracing_core::span::Attributes;
use tracing_log::AsLog;
use tracing_subscriber::fmt::MakeWriter;
use tracing_subscriber::layer::Context;
use tracing_subscriber::registry::SpanRef;
use tracing_subscriber::Layer;
const BUNYAN_VERSION: &str = "v";
const LEVEL: &str = "level";
const NAME: &str = "name";
const HOSTNAME: &str = "hostname";
const PID: &str = "pid";
const TIME: &str = "time";
const MESSAGE: &str = "msg";
const _SOURCE: &str = "src";
fn to_bunyan_level(level: &Level) -> u16 {
match level.as_log() {
log::Level::Error => 50,
log::Level::Warn => 40,
log::Level::Info => 30,
log::Level::Debug => 20,
log::Level::Trace => 10,
}
}
pub struct BunyanFormattingLayer<W: MakeWriter + 'static> {
make_writer: W,
pid: u32,
hostname: String,
bunyan_version: u8,
name: String,
}
impl<W: MakeWriter + 'static> BunyanFormattingLayer<W> {
pub fn new(name: String, make_writer: W) -> Self {
Self {
make_writer,
name,
pid: std::process::id(),
hostname: gethostname::gethostname().to_string_lossy().into_owned(),
bunyan_version: 0,
}
}
fn serialize_bunyan_core_fields(
&self,
map_serializer: &mut impl SerializeMap<Error = serde_json::Error>,
message: &str,
level: &Level,
) -> Result<(), std::io::Error> {
map_serializer.serialize_entry(BUNYAN_VERSION, &self.bunyan_version)?;
map_serializer.serialize_entry(NAME, &self.name)?;
map_serializer.serialize_entry(MESSAGE, &message)?;
map_serializer.serialize_entry(LEVEL, &to_bunyan_level(level))?;
map_serializer.serialize_entry(HOSTNAME, &self.hostname)?;
map_serializer.serialize_entry(PID, &self.pid)?;
map_serializer.serialize_entry(TIME, &chrono::Utc::now().to_rfc3339())?;
Ok(())
}
fn serialize_span<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>>(
&self,
span: &SpanRef<S>,
ty: Type,
) -> Result<Vec<u8>, std::io::Error> {
let mut buffer = Vec::new();
let mut serializer = serde_json::Serializer::new(&mut buffer);
let mut map_serializer = serializer.serialize_map(None)?;
let message = format_span_context(&span, ty);
self.serialize_bunyan_core_fields(&mut map_serializer, &message, span.metadata().level())?;
let extensions = span.extensions();
if let Some(visitor) = extensions.get::<JsonStorage>() {
for (key, value) in visitor.values() {
map_serializer.serialize_entry(key, value)?;
}
}
map_serializer.end()?;
Ok(buffer)
}
fn emit(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> {
buffer.write_all(b"\n")?;
self.make_writer.make_writer().write_all(&buffer)
}
}
#[derive(Clone, Debug)]
pub enum Type {
EnterSpan,
ExitSpan,
Event,
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self {
Type::EnterSpan => "START",
Type::ExitSpan => "END",
Type::Event => "EVENT",
};
write!(f, "{}", repr)
}
}
fn format_span_context<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>>(
span: &SpanRef<S>,
ty: Type,
) -> String {
format!("[{} - {}]", span.metadata().name().to_uppercase(), ty)
}
fn format_event_message<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>>(
current_span: &Option<SpanRef<S>>,
event: &Event,
event_visitor: &JsonStorage<'_>,
) -> String {
let mut message = event_visitor
.values()
.get("message")
.map(|v| match v {
Value::String(s) => Some(s.as_str()),
_ => None,
})
.flatten()
.unwrap_or_else(|| event.metadata().target())
.to_owned();
if let Some(span) = ¤t_span {
message = format!("{} {}", format_span_context(span, Type::Event), message);
}
message
}
impl<S, W> Layer<S> for BunyanFormattingLayer<W>
where
S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
W: MakeWriter + 'static,
{
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
let current_span = ctx.lookup_current();
let mut event_visitor = JsonStorage::default();
event.record(&mut event_visitor);
let format = || {
let mut buffer = Vec::new();
let mut serializer = serde_json::Serializer::new(&mut buffer);
let mut map_serializer = serializer.serialize_map(None)?;
let message = format_event_message(¤t_span, event, &event_visitor);
self.serialize_bunyan_core_fields(
&mut map_serializer,
&message,
event.metadata().level(),
)?;
for (key, value) in event_visitor
.values()
.iter()
.filter(|(&key, _)| key != "message")
{
map_serializer.serialize_entry(key, value)?;
}
if let Some(span) = ¤t_span {
let extensions = span.extensions();
if let Some(visitor) = extensions.get::<JsonStorage>() {
for (key, value) in visitor.values() {
map_serializer.serialize_entry(key, value)?;
}
}
}
map_serializer.end()?;
Ok(buffer)
};
let result: std::io::Result<Vec<u8>> = format();
if let Ok(formatted) = result {
let _ = self.emit(formatted);
}
}
fn new_span(&self, _attrs: &Attributes, id: &Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("Span not found, this is a bug");
if let Ok(serialized) = self.serialize_span(&span, Type::EnterSpan) {
let _ = self.emit(serialized);
}
}
fn on_close(&self, id: Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("Span not found, this is a bug");
if let Ok(serialized) = self.serialize_span(&span, Type::ExitSpan) {
let _ = self.emit(serialized);
}
}
}