tokio-rs / tracing

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

Enrich events with a template string without interpolation #2816

Open Jgfrausing opened 9 months ago

Jgfrausing commented 9 months ago

Feature Request

Crates

Motivation

It would be nice to have the option to enrich events with a template field, which would be the log line before it is interpolated. The suggestion is to have the following

let a = 10;
let b = 20;
tracing::info!(me = "im a me", ?a, "info {}, {}", b, (a + b));

output this:

// current implementation
2023-11-23T08:59:02.722507Z  INFO main: info 20, 30 me="im a me" a=10
// suggested feature
2023-11-23T08:59:02.722923Z  INFO main: info 20, 30 template="info {}, {}" me="im a me" a=10

This would allow log statements to be grouped by the reason and not the specifics. File+Line number can only guarantee this within the same release.

Proposal

A feature would be sufficient such that it is an opt-in option. I have tried to extend info! using a wrapper macro, but have been unable to maintain the same syntax.

#[macro_export]
macro_rules! info {
    ($($key:ident=$value:tt,)* $(?$pre_fmt:tt,)* :$fmt:expr $(, $arg:tt)*) => ({
        tracing::info!(template=$fmt, $($key= $value,)* $(?$pre_fmt,)* $fmt $(, $arg)*);
    });
}

This would be triggered using info!(me="im a me", ?a, : "info {}, {}", b, (a+b));

With my limited skills in macroing, the above has a few drawbacks:

Alternative solution

It might be (probably is) a better option to update the underlying info or event macro instead of wrapping them.