Skip to content

Commit f23de16

Browse files
wyfoJoseph Perezhawkw
authored andcommitted
tracing: allow constant field names in macros (#2617)
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 <[email protected]> Co-authored-by: Eliza Weisman <[email protected]>
1 parent 156c609 commit f23de16

File tree

4 files changed

+206
-69
lines changed

4 files changed

+206
-69
lines changed

tracing/src/lib.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,19 @@
319319
//! # }
320320
//!```
321321
//!
322+
//! Constant expressions can also be used as field names. Constants
323+
//! must be enclosed in curly braces (`{}`) to indicate that the *value*
324+
//! of the constant is to be used as the field name, rather than the
325+
//! constant's name. For example:
326+
//! ```
327+
//! # use tracing::{span, Level};
328+
//! # fn main() {
329+
//! const RESOURCE_NAME: &str = "foo";
330+
//! // this span will have the field `foo = "some_id"`
331+
//! span!(Level::TRACE, "get", { RESOURCE_NAME } = "some_id");
332+
//! # }
333+
//!```
334+
//!
322335
//! The `?` sigil is shorthand that specifies a field should be recorded using
323336
//! its [`fmt::Debug`] implementation:
324337
//! ```

0 commit comments

Comments
 (0)