Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tracing: add record! macro #2926

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions 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()
}
16 changes: 16 additions & 0 deletions tracing/src/macros.rs
Expand Up @@ -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);
}};
}