Skip to main content

zebrad/components/tracing/
format.rs

1//! The text and JSON log formats.
2//!
3//! The JSON format writes one object per line, with these keys, in this order:
4//!
5//! - `timestamp`: RFC 3339 UTC time, with microseconds
6//! - `level`: `TRACE`, `DEBUG`, `INFO`, `WARN`, or `ERROR`
7//! - `severity`: the same level as a Google Cloud Logging severity
8//! - `message`
9//! - `target`: the module that logged the event
10//! - the event's fields
11//! - `spans`: the spans the event happened in, outermost first, if any
12//! - `code.file.path` and `code.line.number`, if known
13//! - `trace_id` and `span_id`, if the event is in a sampled OpenTelemetry trace
14//!
15//! An event field whose name is one of these keys is written as `field.<name>`.
16
17use std::{
18    cell::RefCell,
19    fmt::{self, Write as _},
20};
21
22use tracing::{
23    field::{Field, Visit},
24    span, Event, Level, Subscriber,
25};
26use tracing_log::NormalizeEvent;
27use tracing_subscriber::{
28    field::RecordFields,
29    fmt::{
30        format::{self, DefaultFields, Format, Full, Writer},
31        time::SystemTime,
32        FmtContext, FormatEvent, FormatFields, FormattedFields,
33    },
34    registry::LookupSpan,
35};
36
37/// The longest field value written, in bytes after JSON escaping. Longer values are truncated.
38const MAX_VALUE_LEN: usize = 4 * 1024;
39
40/// The longest line written, in bytes.
41///
42/// Container runtimes split longer lines, which breaks them as JSON.
43const MAX_LINE_LEN: usize = 16 * 1024 - 1;
44
45/// Marks a truncated value.
46const TRUNCATED: &str = "...[truncated]";
47
48/// Integers further from zero than this are written as strings, because many JSON parsers,
49/// including Google Cloud Logging's, read numbers as 64-bit floats.
50const MAX_EXACT_INTEGER: u64 = 1 << 53;
51
52/// The keys of every line. Event fields with these names are renamed.
53const RESERVED_KEYS: &[&str] = &[
54    "timestamp",
55    "level",
56    "severity",
57    "message",
58    "target",
59    "spans",
60    "code.file.path",
61    "code.line.number",
62    "trace_id",
63    "span_id",
64];
65
66/// Formats events in the configured [`LogFormat`](super::LogFormat).
67#[derive(Debug)]
68pub enum EventFormat {
69    /// Human-readable text.
70    Text(Format<Full, SystemTime>),
71
72    /// One JSON object per line.
73    Json,
74}
75
76impl EventFormat {
77    /// Returns the event format and its matching field format.
78    pub fn new(format: super::LogFormat) -> (Self, FieldFormat) {
79        match format {
80            super::LogFormat::Text => (Self::Text(format::format()), FieldFormat::Text),
81            super::LogFormat::Json => (Self::Json, FieldFormat::Json),
82        }
83    }
84}
85
86/// Formats span fields to match the [`EventFormat`].
87///
88/// Layers that store span fields, such as `ErrorLayer`, must use this format too, so the
89/// fields are formatted once and later updates reach every layer.
90#[derive(Copy, Clone, Debug)]
91pub enum FieldFormat {
92    /// `name=value` pairs.
93    Text,
94
95    /// The inside of a JSON object, such as `"name":"value","other":1`.
96    Json,
97}
98
99impl<'writer> FormatFields<'writer> for FieldFormat {
100    fn format_fields<R: RecordFields>(&self, writer: Writer<'writer>, fields: R) -> fmt::Result {
101        match self {
102            Self::Text => DefaultFields::new().format_fields(writer, fields),
103            Self::Json => {
104                let mut writer = writer;
105                let mut visitor = JsonVisitor::new(&mut writer, Fields::Span, true);
106                fields.record(&mut visitor);
107                visitor.result
108            }
109        }
110    }
111
112    fn add_fields(
113        &self,
114        current: &'writer mut FormattedFields<Self>,
115        fields: &span::Record<'_>,
116    ) -> fmt::Result {
117        let first = current.fields.is_empty();
118
119        match self {
120            Self::Text => {
121                if !first {
122                    current.fields.push(' ');
123                }
124                DefaultFields::new().format_fields(current.as_writer(), fields)
125            }
126            Self::Json => {
127                let mut writer = current.as_writer();
128                let mut visitor = JsonVisitor::new(&mut writer, Fields::Span, first);
129                fields.record(&mut visitor);
130                visitor.result
131            }
132        }
133    }
134}
135
136impl<S> FormatEvent<S, FieldFormat> for EventFormat
137where
138    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
139{
140    fn format_event(
141        &self,
142        ctx: &FmtContext<'_, S, FieldFormat>,
143        mut writer: Writer<'_>,
144        event: &Event<'_>,
145    ) -> fmt::Result {
146        match self {
147            Self::Text(format) => format.format_event(ctx, writer, event),
148            Self::Json => {
149                thread_local! {
150                    static LINE: RefCell<String> = const { RefCell::new(String::new()) };
151                }
152
153                LINE.with(|line| {
154                    // A field's `Debug` implementation can log, which formats another line on
155                    // this thread while the buffer is borrowed.
156                    let mut reentrant_line = String::new();
157                    let mut borrowed = line.try_borrow_mut();
158                    let line = match borrowed.as_mut() {
159                        Ok(line) => &mut **line,
160                        Err(_) => &mut reentrant_line,
161                    };
162                    line.clear();
163
164                    write_json_line(line, ctx, event)?;
165                    if line.len() > MAX_LINE_LEN {
166                        line.clear();
167                        write_truncated_json_line(line, event)?;
168                    }
169
170                    writer.write_str(line)?;
171                    writeln!(writer)
172                })
173            }
174        }
175    }
176}
177
178/// Writes `event` as a JSON object, without a line break.
179fn write_json_line<S>(
180    line: &mut String,
181    ctx: &FmtContext<'_, S, FieldFormat>,
182    event: &Event<'_>,
183) -> fmt::Result
184where
185    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
186{
187    let normalized = event.normalized_metadata();
188    let metadata = normalized.as_ref().unwrap_or_else(|| event.metadata());
189
190    write_fixed_keys(line, metadata.level())?;
191
192    // `message` comes first, but tracing doesn't guarantee that it is the first field.
193    line.push_str(",\"message\":");
194    let mut message = MessageVisitor::new(line);
195    event.record(&mut message);
196    message.finish()?;
197
198    line.push_str(",\"target\":");
199    write_json_str(line, metadata.target())?;
200
201    let mut fields = JsonVisitor::new(line, Fields::Event, false);
202    event.record(&mut fields);
203    fields.result?;
204
205    write_spans(line, ctx)?;
206
207    if let Some(file) = metadata.file() {
208        line.push_str(",\"code.file.path\":");
209        write_json_str(line, file)?;
210    }
211    if let Some(number) = metadata.line() {
212        write!(line, ",\"code.line.number\":{number}")?;
213    }
214
215    #[cfg(feature = "opentelemetry")]
216    write_trace_ids(line, ctx)?;
217
218    line.push('}');
219
220    Ok(())
221}
222
223/// Writes the event's spans from the root, as `"spans":[...]`, unless it has none apart from
224/// the global span.
225fn write_spans<S>(line: &mut String, ctx: &FmtContext<'_, S, FieldFormat>) -> fmt::Result
226where
227    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
228{
229    let spans = ctx
230        .event_scope()
231        .into_iter()
232        .flat_map(|scope| scope.from_root())
233        .filter(|span| !is_global_span(span.metadata()));
234
235    let mut first = true;
236    for span in spans {
237        line.push_str(if first { ",\"spans\":[" } else { "," });
238        first = false;
239
240        line.push_str("{\"name\":");
241        write_json_str(line, span.name())?;
242        let extensions = span.extensions();
243        if let Some(fields) = extensions.get::<FormattedFields<FieldFormat>>() {
244            if !fields.is_empty() {
245                line.push(',');
246                line.push_str(fields);
247            }
248        }
249        line.push('}');
250    }
251    if !first {
252        line.push(']');
253    }
254
255    Ok(())
256}
257
258/// Writes an event that is too long for one line, keeping its fixed keys and the start of its
259/// message.
260fn write_truncated_json_line(line: &mut String, event: &Event<'_>) -> fmt::Result {
261    let normalized = event.normalized_metadata();
262    let metadata = normalized.as_ref().unwrap_or_else(|| event.metadata());
263
264    write_fixed_keys(line, metadata.level())?;
265
266    line.push_str(",\"message\":");
267    let mut message = MessageVisitor::new(line);
268    event.record(&mut message);
269    message.finish()?;
270
271    line.push_str(",\"target\":");
272    write_json_str(line, metadata.target())?;
273    line.push_str(",\"truncated\":true}");
274
275    Ok(())
276}
277
278/// Writes the opening brace, `timestamp`, `level`, and `severity`.
279fn write_fixed_keys(line: &mut String, level: &Level) -> fmt::Result {
280    write!(
281        line,
282        "{{\"timestamp\":\"{}\",\"level\":\"{}\",\"severity\":\"{}\"",
283        chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.6fZ"),
284        level.as_str(),
285        severity(level),
286    )
287}
288
289/// Returns the Google Cloud Logging severity for `level`.
290///
291/// Google Cloud Logging reads `severity` and has no `TRACE` or `WARN` severity.
292pub fn severity(level: &Level) -> &'static str {
293    match *level {
294        Level::ERROR => "ERROR",
295        Level::WARN => "WARNING",
296        Level::INFO => "INFO",
297        Level::DEBUG | Level::TRACE => "DEBUG",
298    }
299}
300
301/// Returns `true` for the span Zebra enters for the life of the process.
302///
303/// Every event happens in this span, and its fields don't change, so writing it on each line
304/// would only make lines longer.
305fn is_global_span(metadata: &tracing::Metadata<'_>) -> bool {
306    metadata.name().is_empty() && metadata.target() == "zebrad::application"
307}
308
309/// Writes the IDs of the exported span closest to the event, if that span is sampled.
310///
311/// The OpenTelemetry layer stores each exported span's ID, but not whether it is sampled, so
312/// the IDs come from the context the layer activates when an exported span is entered. That
313/// context belongs to the event only if it is the closest exported span's own context, which
314/// isn't the case for an event with an explicit parent or `parent: None`.
315#[cfg(feature = "opentelemetry")]
316fn write_trace_ids<S>(line: &mut String, ctx: &FmtContext<'_, S, FieldFormat>) -> fmt::Result
317where
318    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
319{
320    use opentelemetry::trace::TraceContextExt;
321    use tracing_opentelemetry::OtelData;
322
323    let Some(exported_span_id) = ctx
324        .event_scope()
325        .into_iter()
326        .flatten()
327        .find_map(|span| span.extensions().get::<OtelData>().map(OtelData::span_id))
328        .flatten()
329    else {
330        return Ok(());
331    };
332
333    opentelemetry::Context::map_current(|context| {
334        let span = context.span();
335        let span_context = span.span_context();
336
337        if span_context.span_id() == exported_span_id && span_context.is_sampled() {
338            write!(
339                line,
340                ",\"trace_id\":\"{}\",\"span_id\":\"{}\"",
341                span_context.trace_id(),
342                exported_span_id,
343            )
344        } else {
345            Ok(())
346        }
347    })
348}
349
350/// Returns a panic as one JSON log line, without a line break.
351///
352/// The line has the same stable keys as other JSON log lines, with `level` `ERROR` and
353/// `severity` `CRITICAL`, and the panic in `exception.type`, `exception.message`, and
354/// `exception.stacktrace`.
355pub(crate) fn json_panic_line(panic_info: &std::panic::PanicHookInfo<'_>) -> String {
356    let payload = panic_info.payload();
357    let message = payload
358        .downcast_ref::<&str>()
359        .copied()
360        .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
361        .unwrap_or("panic with a non-string payload");
362    let thread = std::thread::current();
363    let stacktrace = std::backtrace::Backtrace::force_capture();
364
365    let mut line = String::new();
366    // Writing to a `String` can't fail.
367    let _ = (|| {
368        write!(
369            line,
370            "{{\"timestamp\":\"{}\",\"level\":\"ERROR\",\"severity\":\"CRITICAL\",\"message\":",
371            chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.6fZ"),
372        )?;
373        write_json_str(&mut line, message)?;
374        line.push_str(",\"target\":\"panic\",\"thread\":");
375        write_json_str(&mut line, thread.name().unwrap_or("unnamed"))?;
376        line.push_str(",\"exception.type\":\"panic\",\"exception.message\":");
377        write_json_str(&mut line, message)?;
378
379        let mut location = String::new();
380        if let Some(panic_location) = panic_info.location() {
381            location.push_str(",\"code.file.path\":");
382            write_json_str(&mut location, panic_location.file())?;
383            write!(location, ",\"code.line.number\":{}", panic_location.line())?;
384        }
385
386        // The stack trace gets the rest of the line.
387        const STACKTRACE_KEY: &str = ",\"exception.stacktrace\":\"";
388        let budget = MAX_LINE_LEN
389            .saturating_sub(line.len() + STACKTRACE_KEY.len() + location.len())
390            .saturating_sub("\"}".len() + TRUNCATED.len());
391        line.push_str(STACKTRACE_KEY);
392        let mut escaper = JsonEscaper::new(&mut line, budget);
393        let _ = write!(escaper, "{stacktrace}");
394        escaper.finish()?;
395        line.push('"');
396        line.push_str(&location);
397        line.push('}');
398
399        fmt::Result::Ok(())
400    })();
401
402    line
403}
404
405/// Which fields a [`JsonVisitor`] is writing.
406#[derive(Copy, Clone, Debug, Eq, PartialEq)]
407enum Fields {
408    /// An event's fields, after its message.
409    Event,
410
411    /// A span's fields, inside its object in `spans`.
412    Span,
413}
414
415/// Writes fields as `"name":value` pairs, separated by commas.
416struct JsonVisitor<'a, W: fmt::Write> {
417    writer: &'a mut W,
418    fields: Fields,
419    first: bool,
420    result: fmt::Result,
421}
422
423impl<'a, W: fmt::Write> JsonVisitor<'a, W> {
424    /// Returns a visitor that writes a comma before every field, or before every field but the
425    /// first if `first` is `true`.
426    fn new(writer: &'a mut W, fields: Fields, first: bool) -> Self {
427        Self {
428            writer,
429            fields,
430            first,
431            result: Ok(()),
432        }
433    }
434
435    /// Writes `value` with `write_value` as the value of `field`.
436    fn write(&mut self, field: &Field, write_value: impl FnOnce(&mut W) -> fmt::Result) {
437        let name = field.name();
438
439        if self.result.is_err() || (self.fields == Fields::Event && name == "message") {
440            return;
441        }
442
443        // Fields added by the `log` crate adapter are part of the normalized metadata.
444        if name.starts_with("log.") {
445            return;
446        }
447
448        let renamed = match self.fields {
449            Fields::Event => RESERVED_KEYS.contains(&name),
450            Fields::Span => name == "name",
451        };
452
453        self.result = (|| {
454            if !self.first {
455                self.writer.write_char(',')?;
456            }
457            self.first = false;
458
459            self.writer.write_char('"')?;
460            if renamed {
461                self.writer.write_str("field.")?;
462            }
463            JsonEscaper::new(self.writer, usize::MAX).write_str(name)?;
464            self.writer.write_str("\":")?;
465
466            write_value(self.writer)
467        })();
468    }
469}
470
471impl<W: fmt::Write> Visit for JsonVisitor<'_, W> {
472    fn record_f64(&mut self, field: &Field, value: f64) {
473        self.write(field, |writer| {
474            if value.is_finite() {
475                write!(writer, "{value}")
476            } else {
477                write!(writer, "\"{value}\"")
478            }
479        });
480    }
481
482    fn record_i64(&mut self, field: &Field, value: i64) {
483        self.write(field, |writer| {
484            if value.unsigned_abs() <= MAX_EXACT_INTEGER {
485                write!(writer, "{value}")
486            } else {
487                write!(writer, "\"{value}\"")
488            }
489        });
490    }
491
492    fn record_u64(&mut self, field: &Field, value: u64) {
493        self.write(field, |writer| {
494            if value <= MAX_EXACT_INTEGER {
495                write!(writer, "{value}")
496            } else {
497                write!(writer, "\"{value}\"")
498            }
499        });
500    }
501
502    fn record_bool(&mut self, field: &Field, value: bool) {
503        self.write(field, |writer| write!(writer, "{value}"));
504    }
505
506    fn record_str(&mut self, field: &Field, value: &str) {
507        self.write(field, |writer| write_json_str(writer, value));
508    }
509
510    fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
511        self.write(field, |writer| write_json_display(writer, value));
512    }
513
514    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
515        self.write(field, |writer| write_json_debug(writer, value));
516    }
517}
518
519/// Writes an event's `message` field as a JSON string, or `""` if it has none.
520struct MessageVisitor<'a> {
521    line: &'a mut String,
522    written: bool,
523    result: fmt::Result,
524}
525
526impl<'a> MessageVisitor<'a> {
527    fn new(line: &'a mut String) -> Self {
528        Self {
529            line,
530            written: false,
531            result: Ok(()),
532        }
533    }
534
535    fn finish(self) -> fmt::Result {
536        self.result?;
537        if !self.written {
538            self.line.push_str("\"\"");
539        }
540        Ok(())
541    }
542}
543
544impl Visit for MessageVisitor<'_> {
545    fn record_str(&mut self, field: &Field, value: &str) {
546        if field.name() == "message" && !self.written {
547            self.written = true;
548            self.result = write_json_str(self.line, value);
549        }
550    }
551
552    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
553        if field.name() == "message" && !self.written {
554            self.written = true;
555            self.result = write_json_debug(self.line, value);
556        }
557    }
558}
559
560/// Writes `value` as a JSON string, truncated to [`MAX_VALUE_LEN`].
561fn write_json_str(writer: &mut impl fmt::Write, value: &str) -> fmt::Result {
562    write_json_display(writer, &value)
563}
564
565/// Writes `value`'s `Display` output as a JSON string, truncated to [`MAX_VALUE_LEN`].
566fn write_json_display(writer: &mut impl fmt::Write, value: &dyn fmt::Display) -> fmt::Result {
567    writer.write_char('"')?;
568    let mut escaper = JsonEscaper::new(writer, MAX_VALUE_LEN);
569    // A truncated value stops the `Display` implementation with an error.
570    let _ = write!(escaper, "{value}");
571    escaper.finish()?;
572    writer.write_char('"')
573}
574
575/// Writes `value`'s `Debug` output as a JSON string, truncated to [`MAX_VALUE_LEN`].
576fn write_json_debug(writer: &mut impl fmt::Write, value: &dyn fmt::Debug) -> fmt::Result {
577    writer.write_char('"')?;
578    let mut escaper = JsonEscaper::new(writer, MAX_VALUE_LEN);
579    let _ = write!(escaper, "{value:?}");
580    escaper.finish()?;
581    writer.write_char('"')
582}
583
584/// Escapes text for the inside of a JSON string, and stops once the escaped text reaches a
585/// byte limit.
586struct JsonEscaper<'a, W: fmt::Write> {
587    writer: &'a mut W,
588    remaining: usize,
589    truncated: bool,
590    result: fmt::Result,
591}
592
593impl<'a, W: fmt::Write> JsonEscaper<'a, W> {
594    fn new(writer: &'a mut W, limit: usize) -> Self {
595        Self {
596            writer,
597            remaining: limit,
598            truncated: false,
599            result: Ok(()),
600        }
601    }
602
603    /// Returns any error from the underlying writer, and marks a truncated value.
604    fn finish(self) -> fmt::Result {
605        self.result?;
606        if self.truncated {
607            self.writer.write_str(TRUNCATED)?;
608        }
609        Ok(())
610    }
611}
612
613impl<W: fmt::Write> fmt::Write for JsonEscaper<'_, W> {
614    /// Writes `text` with JSON string escapes, counting the escaped bytes against the limit.
615    fn write_str(&mut self, text: &str) -> fmt::Result {
616        if self.truncated || self.result.is_err() {
617            return Err(fmt::Error);
618        }
619
620        // Escaping makes text at most 6 times longer, so short text skips the limit checks.
621        if text.len().saturating_mul(6) <= self.remaining {
622            self.remaining -= text.len();
623            self.result = escape_json(self.writer, text, &mut self.remaining);
624            return self.result;
625        }
626
627        self.result = (|| {
628            let mut start = 0;
629
630            for (index, byte) in text.bytes().enumerate() {
631                let escape = match byte {
632                    b'"' => Some("\\\""),
633                    b'\\' => Some("\\\\"),
634                    b'\n' => Some("\\n"),
635                    b'\r' => Some("\\r"),
636                    b'\t' => Some("\\t"),
637                    0x00..=0x1f => Some(""),
638                    _ => None,
639                };
640                let len = match escape {
641                    Some("") => 6,
642                    Some(escape) => escape.len(),
643                    None => 1,
644                };
645
646                if len > self.remaining {
647                    let mut end = index;
648                    while !text.is_char_boundary(end) {
649                        end -= 1;
650                    }
651                    self.writer.write_str(&text[start..end])?;
652                    self.truncated = true;
653                    return Ok(());
654                }
655                self.remaining -= len;
656
657                if let Some(escape) = escape {
658                    self.writer.write_str(&text[start..index])?;
659                    if escape.is_empty() {
660                        write!(self.writer, "\\u{byte:04x}")?;
661                    } else {
662                        self.writer.write_str(escape)?;
663                    }
664                    start = index + 1;
665                }
666            }
667
668            self.writer.write_str(&text[start..])
669        })();
670
671        if self.truncated {
672            Err(fmt::Error)
673        } else {
674            self.result
675        }
676    }
677}
678
679/// Writes `text` with JSON string escapes, and subtracts the bytes that escapes add from
680/// `remaining`.
681fn escape_json(writer: &mut impl fmt::Write, text: &str, remaining: &mut usize) -> fmt::Result {
682    let mut start = 0;
683
684    for (index, byte) in text.bytes().enumerate() {
685        let escape = match byte {
686            b'"' => "\\\"",
687            b'\\' => "\\\\",
688            b'\n' => "\\n",
689            b'\r' => "\\r",
690            b'\t' => "\\t",
691            0x00..=0x1f => "",
692            _ => continue,
693        };
694
695        writer.write_str(&text[start..index])?;
696        if escape.is_empty() {
697            write!(writer, "\\u{byte:04x}")?;
698            *remaining -= 5;
699        } else {
700            writer.write_str(escape)?;
701            *remaining -= 1;
702        }
703        start = index + 1;
704    }
705
706    writer.write_str(&text[start..])
707}
708
709#[cfg(test)]
710mod tests;