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
use crate::visitor::{StackdriverEventVisitor, StackdriverVisitor};
use serde::ser::{SerializeMap, Serializer as _};
use serde_json::Value;
use std::{
fmt::{self, Formatter, Write},
io,
};
use tracing_core::{
span::{Attributes, Id},
Event, Subscriber,
};
use tracing_serde::AsSerde;
use tracing_subscriber::{
field::{MakeVisitor, VisitOutput},
fmt::{
time::{ChronoUtc, FormatTime},
FormatFields, FormattedFields, MakeWriter,
},
layer::Context,
registry::LookupSpan,
Layer,
};
pub struct Stackdriver<W = fn() -> io::Stdout>
where
W: MakeWriter,
{
time: ChronoUtc,
writer: W,
fields: StackdriverFields,
}
impl Stackdriver {
pub fn new() -> Self {
Self::default()
}
}
impl<W> Stackdriver<W>
where
W: MakeWriter,
{
pub fn with_writer(writer: W) -> Self {
Self {
time: ChronoUtc::rfc3339(),
writer,
fields: StackdriverFields,
}
}
fn visit<S>(&self, event: &Event, context: Context<S>) -> Result<(), Error>
where
S: Subscriber + for<'span> LookupSpan<'span>,
{
let writer = self.writer.make_writer();
let meta = event.metadata();
let mut time = String::new();
self.time.format_time(&mut time).map_err(|_| Error::Time)?;
let mut serializer = serde_json::Serializer::new(writer);
let mut map = serializer.serialize_map(None)?;
map.serialize_entry("time", &time)?;
map.serialize_entry("severity", &meta.level().as_serde())?;
map.serialize_entry("target", &meta.target())?;
if let Some(span) = context.lookup_current() {
let name = &span.name();
let extensions = span.extensions();
let formatted_fields = extensions
.get::<FormattedFields<StackdriverFields>>()
.expect("No fields!");
let mut fields: Value = serde_json::from_str(&formatted_fields)?;
fields["name"] = serde_json::json!(name);
map.serialize_entry("span", &fields)?;
}
let mut visitor = StackdriverEventVisitor::new(map);
event.record(&mut visitor);
visitor.finish().map_err(Error::from)
}
}
impl Default for Stackdriver {
fn default() -> Self {
Self {
time: ChronoUtc::rfc3339(),
writer: || std::io::stdout(),
fields: StackdriverFields,
}
}
}
impl<S, W> Layer<S> for Stackdriver<W>
where
S: Subscriber + for<'span> LookupSpan<'span>,
W: MakeWriter + 'static,
{
fn new_span(&self, attributes: &Attributes<'_>, id: &Id, context: Context<'_, S>) {
let span = context.span(id).expect("Span not found, this is a bug");
let mut extensions = span.extensions_mut();
if extensions
.get_mut::<FormattedFields<StackdriverFields>>()
.is_none()
{
let mut buffer = String::new();
if self.fields.format_fields(&mut buffer, attributes).is_ok() {
let fmt_fields: FormattedFields<StackdriverFields> = FormattedFields::new(buffer);
extensions.insert(fmt_fields);
}
}
}
#[allow(unused_variables)]
fn on_event(&self, event: &Event, context: Context<S>) {
if let Err(error) = self.visit(event, context) {
#[cfg(test)]
eprintln!("{}", &error)
}
}
}
struct StackdriverFields;
impl<'a> MakeVisitor<&'a mut dyn Write> for StackdriverFields {
type Visitor = StackdriverVisitor<'a>;
#[inline]
fn make_visitor(&self, target: &'a mut dyn Write) -> Self::Visitor {
StackdriverVisitor::new(target)
}
}
#[derive(Debug)]
enum Error {
Formatting(fmt::Error),
Serialization(serde_json::Error),
Time,
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
match self {
Self::Formatting(error) => write!(formatter, "{}", &error),
Self::Serialization(error) => write!(formatter, "{}", &error),
Self::Time => write!(formatter, "Could not format timestamp"),
}
}
}
impl std::error::Error for Error {}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self::Serialization(error)
}
}
impl From<fmt::Error> for Error {
fn from(error: fmt::Error) -> Self {
Self::Formatting(error)
}
}