Trait tracing_subscriber::fmt::FormatEvent [−][src]
pub trait FormatEvent<S, N> where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static, {
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
writer: &mut dyn Write,
event: &Event<'_>
) -> Result;
}
This is supported on crate feature
fmt
only.Expand description
A type that can format a tracing Event
for a fmt::Write
.
FormatEvent
is primarily used in the context of fmt::Subscriber
or fmt::Layer
. Each time an event is
dispatched to fmt::Subscriber
or fmt::Layer
, the subscriber or layer forwards it to
its associated FormatEvent
to emit a log message.
This trait is already implemented for function pointers with the same
signature as format_event
.
Examples
use std::fmt::{self, Write};
use tracing_core::{Subscriber, 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: Subscriber + 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:
DEBUG yak_shaving::shaver: some-span{field-on-span=foo}: started shaving yak
Required methods
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
writer: &mut dyn Write,
event: &Event<'_>
) -> Result
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
writer: &mut dyn Write,
event: &Event<'_>
) -> Result
Write a log message for Event
in Context
to the given Write
.