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); + }}; +}