pub struct LogContext(/* private fields */);
Expand description
A contextual properties that can be attached to log records.
LogContext
represents a set of key-value pairs that will be
automatically added to log messages when the context is active.
Implementations§
Source§impl LogContext
impl LogContext
Sourcepub fn record(
self,
key: impl Into<Cow<'static, str>>,
value: impl Into<ContextValue>,
) -> Self
pub fn record( self, key: impl Into<Cow<'static, str>>, value: impl Into<ContextValue>, ) -> Self
Adds property to this context.
§Examples
use context_logger::LogContext;
let context = LogContext::new()
.record("user_id", "user-123")
.record("request_id", 42)
.record("is_admin", true);
Sourcepub fn add_record(
key: impl Into<Cow<'static, str>>,
value: impl Into<ContextValue>,
)
pub fn add_record( key: impl Into<Cow<'static, str>>, value: impl Into<ContextValue>, )
Adds property to the current active context.
This is useful for adding context information dynamically without having direct access to the context.
§Note
If there is no active context, this operation will have no effect.
§Examples
use context_logger::{LogContext, ContextValue};
use log::info;
fn process_request() {
// Add context information dynamically
LogContext::add_record("processing_time_ms", 42);
info!("Request processed");
}
let _guard = LogContext::new()
.record("request_id", "req-123")
.enter();
process_request(); // Will log with both request_id and processing_time_ms
Sourcepub fn enter<'a>(self) -> LogContextGuard<'a>
pub fn enter<'a>(self) -> LogContextGuard<'a>
Activating this context, returning a guard that will exit the context when dropped.
§In Asynchronous Code
Warning: in asynchronous code Self::enter
should be used very carefully or avoided entirely.
Holding the drop guard across .await
points will result in incorrect logs:
use context_logger::LogContext;
async fn my_async_fn() {
let ctx = LogContext::new()
.record("request_id", "req-123")
.record("user_id", 42);
// WARNING: This context will remain active until this
// guard is dropped...
let _guard = ctx.enter();
// But this code causing the runtime to switch to another task,
// while remaining in this context.
tokio::task::yield_now().await;
}
Please use the crate::FutureExt::in_log_context
instead.
Trait Implementations§
Source§impl Debug for LogContext
impl Debug for LogContext
Auto Trait Implementations§
impl Freeze for LogContext
impl !RefUnwindSafe for LogContext
impl Send for LogContext
impl Sync for LogContext
impl Unpin for LogContext
impl !UnwindSafe for LogContext
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more