Closed thomaseizinger closed 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.
Oh you are right! I didn't think of omitting the %
sigil.
Feature Request
It happens many times that I'd like to print an
Option<T>
in a log message using theDisplay
implementation ofT
. This isn't possible becauseOption
doesn't implementfmt::Display
. It would be nice iftracing
would have a way to optionally include a field using its display-formatting when the option isSome
and omit it when it isNone
.Crates
tracing
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: