Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sample implementation of FormatEvent #1189

Merged
merged 5 commits into from
Jan 28, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions tracing-subscriber/src/fmt/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,74 @@ use fmt::{Debug, Display};
/// This trait is already implemented for function pointers with the same
/// signature as `format_event`.
///
/// # Examples
///
/// ```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<S, N> FormatEvent<S, N> 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();
///
/// // `FormattedFields` is a a formatted representation of the span's
/// // fields, which is stored in its extensions by the `fmt` layer's
/// // `new_span` method. The fields will have been formatted
/// // by the same field formatter that's provided to the event
/// // formatter in the `FmtContext`.
/// let fields = &ext
/// .get::<FormattedFields<N>>()
/// .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)
/// }
/// }
/// ```
///
/// This formatter will print events like this:
///
/// ```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<S, N>
Expand Down