tokio-rs / tracing

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

Allow `Display` formatting of `Option`s in messages #3054

Closed thomaseizinger closed 3 months ago

thomaseizinger commented 3 months ago

Feature Request

It happens many times that I'd like to print an Option<T> in a log message using the Display implementation of T. This isn't possible because Option doesn't implement fmt::Display. It would be nice if tracing would have a way to optionally include a field using its display-formatting when the option is Some and omit it when it is None.

Crates

Motivation

Concise log messages without duplication.

Proposal

Perhaps a new sigil could be added? I don't know the internals of tracing well enough to propose a good solution.

Alternatives

The only workarounds I know of are:

extremeandy commented 3 months ago

I've been trying to figure out how to get the JSON tracing subscriber to output something like this:

{
    "timestamp": "2024-08-12 14:27:52.454850 UTC",
    "level": "INFO",
    "value": null,
    "target": "hello_world"
}

E.g. I tried:

let value: Option<i32> = None;
info!(value);

It doesn't seem to be possible to get it to output "value": null, only "value": "null".

However, I did notice that passing None caused value to be omitted from the output.

So it seems like what you're saying is possible already by using Option<DisplayValue<T>>.

E.g.

let t: T = ...; // where T: std::fmt::Display
let value = Some(tracing::field::display(t)); // or None to omit
info!(value);

If value is None it will be omitted.

thomaseizinger commented 3 months ago

Oh you are right! I didn't think of omitting the % sigil.