tokio-rs / tracing

Application level tracing for Rust.
https://tracing.rs
MIT License
5.15k stars 673 forks source link

tracing_subscriber: add additional fields for printing to json fmt subscriber #2943

Open mladedav opened 2 months ago

mladedav commented 2 months ago

Motivation

Closes #1531

There are scenarios where one wants to add some information to logs emitted by FmtSubscriber, for example adding OpenTelemetry trace ID and span ID.

Solution

This adds an extension which all other subscribers can fill with any fields and then the formatting subscriber can emit these fields alongside the normal ones.

The extension currently wraps a HashMap<String, String>, but it could also feasibly be something like HashMap<String, Box<dyn Value>> but the flexibility of having other types than string permissible here ~didn't seem to offset the additional allocations for this~ String also needs an allocation. Otherwise we could use HashMap<String, serde_json::Value> if this would be considered to be json-specific but I don't think we should go that way now.

Currently, only the Json formatter prints these fields as other ones do not print span attributes at all.

mladedav commented 2 months ago

I've added an example with usage.

mladedav commented 2 months ago

I tried to make this work with dyn Value but I can't figure out how to call Value::record so that I get the json representation. For that I need a Field and the only way I have found to get it is to construct Metadata which is hardly what should happen here.

kaffarell commented 2 months ago

I tried to make this work with dyn Value but I can't figure out how to call Value::record so that I get the json representation. For that I need a Field and the only way I have found to get it is to construct Metadata which is hardly what should happen here.

What do you mean by this?

mladedav commented 2 months ago

Currently, the extension wraps HashMap<String, String> but that means among other things that numbers get represented as strings.

I tried changing that to HashMap<String, Box<Dyn Value>> but couldn't make it work.

When tracing starts to use valuable, it could probably use that instead but for now the string should hopefully be enough.

kaffarell commented 2 months ago

Currently, the extension wraps HashMap<String, String> but that means among other things that numbers get represented as strings.

I tried changing that to HashMap<String, Box<Dyn Value>> but couldn't make it work.

When tracing starts to use valuable, it could probably use that instead but for now the string should hopefully be enough.

ooh, because it's not serializable, right. Anyway strings are fine I guess.