Skip to content

Extra field extension for Json format#3482

Open
Lur1an wants to merge 1 commit intotokio-rs:mainfrom
Lur1an:feature/extra-fields-json
Open

Extra field extension for Json format#3482
Lur1an wants to merge 1 commit intotokio-rs:mainfrom
Lur1an:feature/extra-fields-json

Conversation

@Lur1an
Copy link

@Lur1an Lur1an commented Feb 24, 2026

This PR introduces a way for users to provide a generic field injector implementation to augment json log events.

Motivation

This solves #1531 by allowing anyone to extend the fields of the JSON records as they see fit.
This is a common problem across the rust ecosystem and often ends up with hacking or building a new formatter directly to get trace_id and span_id into logs.

Solution

pub trait ExtraFields {
    /// Write additional entries into the JSON serializer.
    fn format_extra_fields<S, N, M>(
        &self,
        ctx: &FmtContext<'_, S, N>,
        event: &Event<'_>,
        serializer: &mut M,
    ) -> serde_json::Result<()>
    where
        S: Subscriber + for<'a> LookupSpan<'a>,
        N: for<'a> FormatFields<'a> + 'static,
        M: SerializeMap<Ok = (), Error = serde_json::Error>;
}

Thanks to this it is now possible to build things like a trace_id injector:

impl ExtraFields for OtelTraceId {
    fn format_extra_fields<S, N, M>(
        &self,
        ctx: &FmtContext<'_, S, N>,
        _event: &Event<'_>,
        serializer: &mut M,
    ) -> serde_json::Result<()>
    where
        S: Subscriber + for<'a> LookupSpan<'a>,
        N: for<'a> FormatFields<'a> + 'static,
        M: SerializeMap<Ok = (), Error = serde_json::Error>,
    {
        if let Some(span) = ctx.lookup_current() {
            let extensions = span.extensions();
            if let Some(otel) = extensions.get::<OtelData>() {
                let trace_id = otel.parent_cx.span().span_context().trace_id();
                serializer.serialize_entry("trace_id", &trace_id.to_string())?;
            }
        }
        Ok(())
    }
}

The trait is kept generic and given direct access to the serializer, event and context for both efficiency and flexibility.

@Lur1an Lur1an requested review from a team, hawkw and hds as code owners February 24, 2026 00:05
@Lur1an Lur1an force-pushed the feature/extra-fields-json branch from 2502df5 to 05c8dca Compare February 24, 2026 00:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant