macro_rules! add_fields {
( $($args:tt)* ) => { ... };
}logging or metrics or tracing or memory-profiling or telemetry-server) and crate feature logging only.Expand description
Adds fields to all the log records, making them context fields.
Calling the method with same field name multiple times updates the key value. There is a small
cost in performance if large numbers of the same field are added, which then must be
deduplicated at runtime. For that reason, as well as the fact that there is a danger of stack
overflow if add_fields! is called an extremely large number of times on the same logger,
there is an internal counter which will trigger a panic if a limit of (currently) 1000 calls on
a single logger is reached.
To avoid this panic, make sure to only use add_fields! for fields that will remain relatively
static (under 1000 updates over the lifetime of any given logger).
Certain added fields may not be present in the resulting logs if
LoggingSettings::redact_keys is used.
ยงExamples
use foundations::telemetry::TelemetryContext;
use foundations::telemetry::log::{self, TestLogRecord};
use foundations::telemetry::settings::Level;
// Test context is used for demonstration purposes to show the resulting log records.
let ctx = TelemetryContext::test();
let _scope = ctx.scope();
log::warn!("Hello with one field"; "foo" => "bar");
log::add_fields!("ctx_field1" => 42, "ctx_field2" => "baz");
log::warn!("With context fields"; "foo" => "bar");
// Update the context field value
log::add_fields!("ctx_field1" => 43);
log::warn!("One more with context fields");
assert_eq!(*ctx.log_records(), &[
TestLogRecord {
level: Level::Warning,
message: "Hello with one field".into(),
fields: vec![("foo".into(), "bar".into())]
},
TestLogRecord {
level: Level::Warning,
message: "With context fields".into(),
fields: vec![
("ctx_field2".into(), "baz".into()),
("ctx_field1".into(), "42".into()),
("foo".into(), "bar".into())
]
},
TestLogRecord {
level: Level::Warning,
message: "One more with context fields".into(),
fields: vec![
("ctx_field1".into(), "43".into()),
("ctx_field2".into(), "baz".into()),
]
}
]);