Skip to content

Commit

Permalink
subscriber: nicer fmt::Debug for Layered (tokio-rs#1528)
Browse files Browse the repository at this point in the history
Currently, `Layered` only implements `fmt::Debug` if the outer layer,
the inner layer, *and* the subscriber type parameters all implement
`fmt::Debug`. However, in the case of a `Layered` with two `Layer`s, the
subscriber itself is not present --- it's only a `PhantomData`. So the
`fmt::Debug` implementation should be possible when only the actual
`layer` and `inner` values are `Debug`. For the `PhantomData`, we can
just print the type name.

This means that `Layered` consisting of two `Layer`s and no `Subscriber`
will now implement `Debug` if the `Layer`s are `Debug`, regardless of
the subscriber type. When the `Layered` is a `Layer` and a `Subscriber`,
the behavior will be the same, because the separate `PhantomData`
subscriber type param is always the same as the type of the inner
subscriber.

Because printing the whole type name of the subscriber is potentially
verbose (e.g. when the subscriber itself is a big pile of layers), we
only include it in alt-mode.
  • Loading branch information
hawkw authored and kaffarell committed May 22, 2024
1 parent 4a0e16f commit 182449a
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions tracing-subscriber/src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ use tracing_core::{
#[cfg(feature = "registry")]
use crate::registry::Registry;
use crate::registry::{self, LookupSpan, SpanRef};
use std::{any::TypeId, marker::PhantomData};
use std::{
any::{type_name, TypeId},
fmt,
marker::PhantomData,
};

/// A composable handler for `tracing` events.
///
Expand Down Expand Up @@ -557,7 +561,7 @@ pub struct Context<'a, S> {
///
/// [`Layer`]: ../layer/trait.Layer.html
/// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html
#[derive(Clone, Debug)]
#[derive(Clone)]
pub struct Layered<L, I, S = I> {
layer: L,
inner: I,
Expand Down Expand Up @@ -942,6 +946,25 @@ where
// }
// }

impl<A, B, S> fmt::Debug for Layered<A, B, S>
where
A: fmt::Debug,
B: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let alt = f.alternate();
let mut s = f.debug_struct("Layered");
s.field("layer", &self.layer).field("inner", &self.inner);
if alt {
s.field(
"subscriber",
&format_args!("PhantomData<{}>", type_name::<S>()),
);
};
s.finish()
}
}

// === impl SubscriberExt ===

impl<S: Subscriber> crate::sealed::Sealed for S {}
Expand Down

0 comments on commit 182449a

Please sign in to comment.