Skip to content

Commit

Permalink
tracing: allow constant field names in macros (#2617)
Browse files Browse the repository at this point in the history
I've found myself in the case where I wanted to have customized event field name
for different trait implementations. In fact, these implementations are
completely unrelated (in separate applications), so, in this use case, I find
more readable to have `foo="some_id"` and `bar=16` instead of `resource="foo"
value="some_id"` and `resource=bar value=16`

Because events only accept identifier or literal as field name, this is quite
cumbersome/impossible to do. A simple solution could be to make events accept
constant expression too; in my use case, I could then add a associated constant
to my trait.

This PR proposes a new syntax for using constant field names:
```rust
tracing::debug!({ CONSTANT_EXPR } = "foo");
```
This is the same syntax than constant expression, so it should be quite intuitive.

To avoid constant expression names conflict, internal variables of macro
expansion have been prefixed with `__`, e.g. `__CALLSITE`.

Co-authored-by: Joseph Perez <joseph.perez@numberly.com>
Co-authored-by: Eliza Weisman <eliza@buoyant.io>
  • Loading branch information
3 people authored and davidbarsky committed Sep 27, 2023
1 parent 156c609 commit c56682a
Show file tree
Hide file tree
Showing 4 changed files with 206 additions and 69 deletions.
13 changes: 13 additions & 0 deletions tracing/src/lib.rs
Expand Up @@ -319,6 +319,19 @@
//! # }
//!```
//!
//! Constant expressions can also be used as field names. Constants
//! must be enclosed in curly braces (`{}`) to indicate that the *value*
//! of the constant is to be used as the field name, rather than the
//! constant's name. For example:
//! ```
//! # use tracing::{span, Level};
//! # fn main() {
//! const RESOURCE_NAME: &str = "foo";
//! // this span will have the field `foo = "some_id"`
//! span!(Level::TRACE, "get", { RESOURCE_NAME } = "some_id");
//! # }
//!```
//!
//! The `?` sigil is shorthand that specifies a field should be recorded using
//! its [`fmt::Debug`] implementation:
//! ```
Expand Down

0 comments on commit c56682a

Please sign in to comment.