Global fields to always log on any event in tracing_subscriber

Hi everyone.
Is it possible somehow add global fields that will be logged on each event using tracing_subscriber crate ?

This is what I have for layer:

    let layer = tracing_subscriber::fmt::layer()


macro call:
info!(test = 1, test = 2, "Test message");
gives next message:
{"timestamp":"2022-09-23T09:05:40.716435Z","level":"INFO","message":"Test message","test":1,"test":2,"target":"test"}

What I want is to make any macro call for any LEVEL in any place to produce additional fields:
so the same call:
info!(test = 1, test = 2, "Test message");
will produce next message:
{"timestamp":"2022-09-23T09:05:40.716435Z","level":"INFO","message":"Test message","test":1,"test":2,"target":"test", "global_field_0": "global_field_value_0", "global_field_1": "global_field_value_1"}.

Will appreciate on suggestions on how to do it.

I see there is an open issue:

It seems the solution will be to write my own struct that implements Layer.

What about creating a span at the top of your main() containing all the global fields? That way they'll be inherited by every message like normal.

Hi, sorry for late reply. I've just implemented trait FormatEvent from tracing_subscriber and use my implementation with tracing_subscriber::fmt::layer(). So I can add/remove/rename fields.
If I use span from main function those additional fields will be recorded in current_span or in a span_list and I need them to be on the same level as all other fields in event.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.