From d6fb4a9ff39c9ca9059dfc70b5dbca8148f500c1 Mon Sep 17 00:00:00 2001 From: Marcus Pettersen Irgens Date: Wed, 3 Apr 2024 17:54:04 +0200 Subject: [PATCH] tracing: add record! macro Add a macro that provides a more consise way of recording a new value for a field. Example usage: ```rust fn my_function() { let my_new_value = my_other_function(); // Using the current API: tracing::Span::current().record("example", tracing::field::debug(my_new_value)); // Using this proposal: tracing::record!("example", ?my_new_value); } ``` --- examples/examples/record.rs | 29 +++++++++++++++++++++++++++++ tracing/src/macros.rs | 16 ++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 examples/examples/record.rs diff --git a/examples/examples/record.rs b/examples/examples/record.rs new file mode 100644 index 000000000..c6bc85a35 --- /dev/null +++ b/examples/examples/record.rs @@ -0,0 +1,29 @@ +//! An example of using the [`record`][crate::record] macro to add a field to a span. +#![deny(rust_2018_idioms)] +#![allow(clippy::try_err)] + +use rand::{seq::SliceRandom, thread_rng}; +use tracing::{instrument, record}; + +fn main() { + tracing_subscriber::fmt() + // enable everything + .with_max_level(tracing::Level::TRACE) + // sets this to be the default, global collector for this application. + .init(); + + do_something(); +} + +#[instrument(fields(important_number = tracing::field::Empty))] +fn do_something() { + let important_number = get_important_number(); + record!("important_number", %important_number); + + tracing::info!("log entry with important number"); +} + +fn get_important_number() -> u8 { + let numbers = [42, 13]; + *numbers.choose(&mut thread_rng()).unwrap() +} diff --git a/tracing/src/macros.rs b/tracing/src/macros.rs index 5de45cb75..d6cf4fb73 100644 --- a/tracing/src/macros.rs +++ b/tracing/src/macros.rs @@ -3160,3 +3160,19 @@ macro_rules! if_log_enabled { } }; } + +#[doc(hidden)] +#[macro_export] +macro_rules! record { + ($field:expr, %$value:expr) => { + $crate::record!($field, ::tracing::field::display(&$value)) + }; + ($field:expr, ?$value:expr) => { + $crate::record!($field, ::tracing::field::debug(&$value)) + }; + ($field:expr, $value:expr) => {{ + #[allow(unused)] + use ::tracing::field::{debug, display}; + ::tracing::Span::current().record($field, $value); + }}; +}