Skip to content

Commit 2d27703

Browse files
authored
subscriber: fix accessing the field formatter from FmtContext (#1081) (#1082)
This backports PR #1081 from v0.2.x. Since this has already been approved on master, I'll just go ahead and merge it when CI passes. ## Motivation Currently, the `FmtContext` type implements `FormatFields` using the subscriber's field formatter. However, this is difficult to use. The `FmtContext` may _not_ be passed to functions expecting a `for<'writer> FormatFields<'writer>`, because it only implements `FormatFields` for its _own_ lifetime. This means the writer must have the same lifetime as the context, which is not correct. ## Solution This branch fixes this by changing the impl of `FormatFields` for `FmtContext` to be generic over both the context's lifetime _and_ the field formatter's lifetime. Additionally, I've added a method for borrowing the actual field formatter as its concrete type, in case the `FormatEvent` impl puts additional constraints on its type or is only implemented for a specific named type, and wants to actually _use_ that type.
1 parent 8bdc6c3 commit 2d27703

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

tracing-subscriber/src/fmt/fmt_layer.rs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -784,14 +784,14 @@ impl<'a, S, N> fmt::Debug for FmtContext<'a, S, N> {
784784
}
785785
}
786786

787-
impl<'a, S, N> FormatFields<'a> for FmtContext<'a, S, N>
787+
impl<'cx, 'writer, S, N> FormatFields<'writer> for FmtContext<'cx, S, N>
788788
where
789789
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
790-
N: for<'writer> FormatFields<'writer> + 'static,
790+
N: FormatFields<'writer> + 'static,
791791
{
792792
fn format_fields<R: RecordFields>(
793793
&self,
794-
writer: &'a mut dyn fmt::Write,
794+
writer: &'writer mut dyn fmt::Write,
795795
fields: R,
796796
) -> fmt::Result {
797797
self.fmt_fields.format_fields(writer, fields)
@@ -879,6 +879,17 @@ where
879879
{
880880
self.ctx.scope()
881881
}
882+
883+
/// Returns the [field formatter] configured by the subscriber invoking
884+
/// `format_event`.
885+
///
886+
/// The event formatter may use the returned field formatter to format the
887+
/// fields of any events it records.
888+
///
889+
/// [field formatter]: FormatFields
890+
pub fn field_format(&self) -> &N {
891+
self.fmt_fields
892+
}
882893
}
883894

884895
struct Timings {

0 commit comments

Comments
 (0)