pub struct ContextLogger { /* private fields */ }
Expand description
A logger wrapper that enhances log records with contextual properties.
ContextLogger
wraps an existing logging implementation and adds additional
context properties to log records. These context properties are taken from the
current context stack, which is managed by the LogContext
type.
§Example
use log::{info, LevelFilter};
use context_logger::{ContextLogger, LogContext};
// Create a logger.
let env_logger = env_logger::builder().build();
let max_level = env_logger.filter();
// Wrap it with ContextLogger to enable context propagation.
let context_logger = ContextLogger::new(env_logger);
// Initialize the resulting logger.
context_logger.init(max_level);
// Create a context with properties
let ctx = LogContext::new()
.record("request_id", "req-123")
.record("user_id", 42);
// Use the context while logging
let _guard = ctx.enter();
info!("Processing request"); // Will include request_id and user_id properties
See LogContext
for more information on how to create and manage context properties.
Implementations§
Source§impl ContextLogger
impl ContextLogger
Sourcepub fn new<L>(inner: L) -> Selfwhere
L: Log + 'static,
pub fn new<L>(inner: L) -> Selfwhere
L: Log + 'static,
Creates a new ContextLogger
that wraps the given logging implementation.
The inner logger will receive log records enhanced with context properties from the current context stack.
Sourcepub fn init(self, max_level: LevelFilter)
pub fn init(self, max_level: LevelFilter)
Initializes the global logger with the context logger.
This should be called early in the execution of a Rust program. Any log events that occur before initialization will be ignored.
§Panics
Panics if a logger has already been set.
Sourcepub fn try_init(self, max_level: LevelFilter) -> Result<(), SetLoggerError>
pub fn try_init(self, max_level: LevelFilter) -> Result<(), SetLoggerError>
Initializes the global logger with the context logger.
This should be called early in the execution of a Rust program. Any log events that occur before initialization will be ignored.
§Errors
Returns an error if a logger has already been set.