From 7a16586fd27da947eefb105b339020b9eaadad44 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Wed, 13 Jan 2021 22:25:54 +0100 Subject: [PATCH] Add sample implementation of `FormatEvent` The docs previously didn't provide much help implementing `FormatEvent`. Especially getting access to fields on spans could be tricky unless the user was aware of `FormattedFields`. This updates the docs with a basic, but working, example. --- tracing-subscriber/src/fmt/format/mod.rs | 61 ++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tracing-subscriber/src/fmt/format/mod.rs b/tracing-subscriber/src/fmt/format/mod.rs index e223aa7bc7..a4d7e0e287 100644 --- a/tracing-subscriber/src/fmt/format/mod.rs +++ b/tracing-subscriber/src/fmt/format/mod.rs @@ -46,6 +46,67 @@ use fmt::{Debug, Display}; /// This trait is already implemented for function pointers with the same /// signature as `format_event`. /// +/// # Example implementation +/// +/// ```rust +/// use std::fmt::{self, Write}; +/// use tracing_core::{Collect, Event}; +/// use tracing_subscriber::fmt::{FormatEvent, FormatFields, FmtContext, FormattedFields}; +/// use tracing_subscriber::registry::LookupSpan; +/// +/// struct MyFormatter; +/// +/// impl FormatEvent for MyFormatter +/// where +/// S: Collect + for<'a> LookupSpan<'a>, +/// N: for<'a> FormatFields<'a> + 'static, +/// { +/// fn format_event( +/// &self, +/// ctx: &FmtContext<'_, S, N>, +/// writer: &mut dyn fmt::Write, +/// event: &Event<'_>, +/// ) -> fmt::Result { +/// // Write level and target +/// let level = *event.metadata().level(); +/// let target = event.metadata().target(); +/// write!( +/// writer, +/// "{} {}: ", +/// level, +/// target, +/// )?; +/// +/// // Write spans and fields of each span +/// ctx.visit_spans(|span| { +/// write!(writer, "{}", span.name())?; +/// +/// let ext = span.extensions(); +/// let fields = &ext +/// .get::>() +/// .expect("will never be `None`"); +/// if !fields.is_empty() { +/// write!(writer, "{{{}}}", fields)?; +/// } +/// write!(writer, ": ")?; +/// +/// Ok(()) +/// })?; +/// +/// // Write fields on the event +/// ctx.field_format().format_fields(writer, event)?; +/// +/// writeln!(writer) +/// } +/// } +/// ``` +/// +/// That will result in events printed like so: +/// +/// ```text +/// DEBUG yak_shaving::shaver: some-span{field-on-span=foo}: started shaving yak +/// ``` +/// /// [`fmt::Collector`]: super::Collector /// [`fmt::Subscriber`]: super::Subscriber pub trait FormatEvent