pub struct ContextLogger { /* private fields */ }Expand description
A logger wrapper that enhances log::Record with scoped fields.
ContextLogger wraps an existing logging implementation and merges
additional fields from the current scope stack into each log::Record.
These fields are taken from the scope stack managed by LogScope.
See the crate-level docs for an overview and examples.
See LogContext for more information on how to create and manage scope
fields.
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 scope fields from the current scope 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.
Sourcepub fn with_default_field(
self,
key: impl Into<Cow<'static, str>>,
value: impl Into<LogValue>,
) -> Self
pub fn with_default_field( self, key: impl Into<Cow<'static, str>>, value: impl Into<LogValue>, ) -> Self
Adds a default field that will be included in every log::Record.
Default fields are automatically merged into each log record, regardless of the current context. They are defined when the logger is created and remain constant throughout the application’s lifetime.
§Behavior with Duplicate Keys
When logging, default fields are added first, followed by fields from the current context. If multiple fields with the same key exist, the behavior depends on the underlying logger implementation. In most implementations, later fields with the same key will typically replace earlier ones.
§Example
use log::{info, LevelFilter};
use context_logger::{ContextLogger, LogContext, LogScope};
// Create a logger with default fields
let logger = ContextLogger::new(env_logger::builder()
.filter_level(log::LevelFilter::Info)
.build())
.with_default_field("service", "api")
.with_default_field("version", "1.0.0");
// Initialize it
logger.init(LevelFilter::Info);
info!("Processing request"); // Will include service="api", version="1.0.0"Sourcepub fn with_default_field_fn<V: Into<LogValue>>(
self,
key: impl Into<Cow<'static, str>>,
f: impl Fn(&Record<'_>) -> V + Send + Sync + 'static,
) -> Self
pub fn with_default_field_fn<V: Into<LogValue>>( self, key: impl Into<Cow<'static, str>>, f: impl Fn(&Record<'_>) -> V + Send + Sync + 'static, ) -> Self
Adds a dynamic default field computed by the given closure for every
log::Record.
Like Self::with_default_field, the field is merged into each log
record. However, unlike the static variant, the value is computed
at log time by invoking the provided closure with the current
log::Record itself. This makes it suitable for fields whose
values are not known upfront, such as timestamps or thread IDs.
Note! The order in which dynamic default field functions are evaluated is not guaranteed.
§Example
Adding a current timestamp.
use chrono::Utc;
use log::{info, LevelFilter};
use context_logger::{ContextLogger, LogValue};
let logger = ContextLogger::new(env_logger::builder()
.filter_level(log::LevelFilter::Info)
.build())
.with_default_field_fn("timestamp", |_record| {
Utc::now().to_rfc3339().to_string()
});
logger.init(LevelFilter::Info);
info!("Hello"); // Will include timestamp="..."