From a90310ee4b7f795f0b732a600a65505366b8dbe4 Mon Sep 17 00:00:00 2001 From: Eliza Weisman Date: Tue, 26 Oct 2021 09:18:25 -0700 Subject: [PATCH] subscriber: don't bail when timestamp formatting fails ## Motivation Currently, `tracing_subscriber::fmt` will bail out of formatting the log line when formatting the timestamp fails. Previously, when timestamps were formatted using the `chrono` crate, this was the correct behavior, as getting the timestamp was infallible, and an error would only be returned if *formatting* the timestamp to the buffer fails. This should never actually happen, because we are writing the timestamp to a string, which should never fail; using `?` is just a bit more efficient than `.expect` because it doesn't require generating unwinding code. However, this is no longer the case when using the `time` crate. In the `time` API, actually getting a timestamp is fallible, and in some cases, will fail. The current code will bail out of formatting the entire log line if getting the timestamp fails, which is not great --- using the wrong timestamp formatter will result in silently dropping all log lines. ## Solution This branch changes the `format_timestamp` method to print `` when the timestamp formatting fails, rather than bailing. This way, we at least print the rest of the log line for the event. This fixes half of the issue described in #1688 (the other half is improving documentation). --- tracing-subscriber/src/fmt/format/mod.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tracing-subscriber/src/fmt/format/mod.rs b/tracing-subscriber/src/fmt/format/mod.rs index c8ca8f8b1d..cf2499572d 100644 --- a/tracing-subscriber/src/fmt/format/mod.rs +++ b/tracing-subscriber/src/fmt/format/mod.rs @@ -609,14 +609,24 @@ impl Format { if self.ansi { let style = Style::new().dimmed(); write!(writer, "{}", style.prefix())?; - self.timer.format_time(writer)?; + + // If getting the timestamp failed, don't bail --- only bail on + // formatting errors. + if self.timer.format_time(writer).is_err() { + writer.write_str("")?; + } + write!(writer, "{} ", style.suffix())?; return Ok(()); } } // Otherwise, just format the timestamp without ANSI formatting. - self.timer.format_time(writer)?; + // If getting the timestamp failed, don't bail --- only bail on + // formatting errors. + if self.timer.format_time(writer).is_err() { + writer.write_str("")?; + } writer.write_char(' ') }