From b7bea6929996cf23290c74938e47cbb0a3ef5b4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Teo=20Klestrup=20R=C3=B6ijezon?= Date: Fri, 9 Jul 2021 05:06:10 +0200 Subject: [PATCH] Display the whole error stack when formatting errors According to the format suggested in https://github.com/tokio-rs/tracing/issues/1347#issuecomment-813674313 Fixes #1347 --- tracing-subscriber/src/fmt/format/mod.rs | 23 ++++++++++++++++++++- tracing-subscriber/src/fmt/format/pretty.rs | 4 ++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/tracing-subscriber/src/fmt/format/mod.rs b/tracing-subscriber/src/fmt/format/mod.rs index 7a551bee46..c28d12b22e 100644 --- a/tracing-subscriber/src/fmt/format/mod.rs +++ b/tracing-subscriber/src/fmt/format/mod.rs @@ -761,7 +761,10 @@ impl<'a> field::Visit for DefaultVisitor<'a> { fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) { if let Some(source) = value.source() { - self.record_debug(field, &format_args!("{}, {}: {}", value, field, source)) + self.record_debug( + field, + &format_args!("{}, {}.sources: {}", value, field, ErrorSourceList(source)), + ) } else { self.record_debug(field, &format_args!("{}", value)) } @@ -806,6 +809,24 @@ impl<'a> fmt::Debug for DefaultVisitor<'a> { } } +/// Renders an error into a list of sources, *including* the error +struct ErrorSourceList<'a>(&'a (dyn std::error::Error + 'static)); + +impl<'a> Display for ErrorSourceList<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_char('[')?; + let mut curr = Some(self.0); + while let Some(curr_err) = curr { + f.write_fmt(format_args!("{}", curr_err))?; + curr = curr_err.source(); + if curr.is_some() { + f.write_str(", ")?; + } + } + f.write_char(']') + } +} + struct FmtCtx<'a, S, N> { ctx: &'a FmtContext<'a, S, N>, span: Option<&'a span::Id>, diff --git a/tracing-subscriber/src/fmt/format/pretty.rs b/tracing-subscriber/src/fmt/format/pretty.rs index ab1180823f..dedacae5da 100644 --- a/tracing-subscriber/src/fmt/format/pretty.rs +++ b/tracing-subscriber/src/fmt/format/pretty.rs @@ -332,12 +332,12 @@ impl<'a> field::Visit for PrettyVisitor<'a> { self.record_debug( field, &format_args!( - "{}, {}{}.source{}: {}", + "{}, {}{}.sources{}: {}", value, bold.prefix(), field, bold.infix(self.style), - source, + ErrorSourceList(source), ), ) } else {