tokio-rs / tracing

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

`info!`/`error!`/`warn!` macros don't accept constants for first field name #2837

Closed tim3z closed 6 months ago

tim3z commented 8 months ago

Version

tracing v0.1.40
    ├── tracing-attributes v0.1.27 (proc-macro)
    └── tracing-core v0.1.32

Platform

macOS 13.6 Darwin HAMACL00492 22.6.0 Darwin Kernel Version 22.6.0: Tue Nov 7 21:40:08 PST 2023; root:xnu-8796.141.3.702.9~2/RELEASE_ARM64_T6000 arm64

stable-aarch64-apple-darwin (default)
rustc 1.74.1 (a28077b28 2023-12-04)

Description

I expected the following sample to compile. The problem is the same on all the different log levels (I tried only info, warn and error)

const FOO: &str = "foo";
fn main() {
    tracing::info!(bar = 42, { FOO } = 23, "tada"); // works
    tracing::event!(tracing::Level::INFO, { FOO } = 23, bar = 42, "tada"); // works, too
    tracing::info!({ FOO } = 23, bar = 42, "tada"); // doesn't compile
}
ItsEthra commented 7 months ago

I don't think they should compile. The same behavior is present in println, format, etc. Because those macros accept a string literal. Also I believe info, warn, error, etc all use format_args internally which also requires a string literal so it just wouldn't be possible.

mladedav commented 6 months ago

This should compile, the docs say that you can use constant expressions as names. There just seems to be an issue with it being the first field because { ... } is already handled specially.

There's a test for this, it just doens't use the constant in the first position so this should probably be expanded and then fixed.

In the meantime, you can put the fields in another set of curly braces which should work as expected:

tracing::info!({{ FOO } = 23, bar = 42}, "tada");