From c09b799f45ff0e6bec9bfd044ab69ab2f6c117f0 Mon Sep 17 00:00:00 2001 From: Eliza Weisman Date: Wed, 27 Jul 2022 14:52:52 -0700 Subject: [PATCH] core: give `SetGlobalDefaultError` a useful `Debug` impl (#2250) ## Motivation When a global default dispatcher has already been set, the `dispatch::set_global_default` function fails with a `SetGlobalDefaultError`. The `fmt::Display` impl for this type includes a message explaining that the error indicates that a global default has already been set, but the `fmt::Debug` impl is derived, and just looks like this: ``` SetGlobalDefaultError { _no_construct: () } ``` which isn't particularly helpful. Unfortunately, when `unwrap()`ping or `expect()`ing a `Result`, the `fmt::Debug` implementation for the error type is used, rather than `fmt::Display`. This means that the error message will not explain to the user why setting the global default dispatcher failed, which is a bummer. ## Solution This branch replaces the derived `Debug` impl with a manually implemented one that prints the same message as the `Display` impl, but formatted like a tuple struct with a single string field. This avoids emitting `Debug` output that's *just* a textual human-readable message, rather than looking like Rust code, but ensures the message is visible to the user when writing code like ```rust tracing::dispatch::set_global_default(foo).unwrap(); ``` The mesasge now looks like: ``` SetGlobalDefaultError("a global default trace dispatcher has already been set") ``` which should be a bit easier to debug. --- tracing-core/src/dispatcher.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/tracing-core/src/dispatcher.rs b/tracing-core/src/dispatcher.rs index 041722c366..a3661817c0 100644 --- a/tracing-core/src/dispatcher.rs +++ b/tracing-core/src/dispatcher.rs @@ -293,14 +293,21 @@ pub fn has_been_set() -> bool { } /// Returned if setting the global dispatcher fails. -#[derive(Debug)] pub struct SetGlobalDefaultError { _no_construct: (), } +impl fmt::Debug for SetGlobalDefaultError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("SetGlobalDefaultError") + .field(&Self::MESSAGE) + .finish() + } +} + impl fmt::Display for SetGlobalDefaultError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.pad("a global default trace dispatcher has already been set") + f.pad(Self::MESSAGE) } } @@ -308,6 +315,10 @@ impl fmt::Display for SetGlobalDefaultError { #[cfg_attr(docsrs, doc(cfg(feature = "std")))] impl error::Error for SetGlobalDefaultError {} +impl SetGlobalDefaultError { + const MESSAGE: &'static str = "a global default trace dispatcher has already been set"; +} + /// Executes a closure with a reference to this thread's current [dispatcher]. /// /// Note that calls to `get_default` should not be nested; if this function is