pub struct Logger { /* private fields */ }
Expand description
Manages, controls and manipulates multiple sinks.
Logger is an entry point for a log to be processed, the Logger::log
method will be called by logging macros.
A Logger:
-
contains one or more sinks, each log will be passed into sinks in sequence;
-
has a level filter of its own, which is not shared with the level filter of sinks;
-
has automatic flushing policies that can be optionally enabled:
- Flush level filter: Flush once when the filter returns
true
for a log. - Flush period: Flush periodically.
These two automatic flushing policies can work at the same time.
- Flush level filter: Flush once when the filter returns
spdlog-rs has a global default_logger
, you can modify it, or configure
a new logger to suit your needs and then replace it. Basically for a
lightweight program, such a global singleton logger is enough. For a complex
program, for example if you have a number of different components, you can
also configure multiple loggers and store them independently inside the
component struct, which allows different components to have different
approaches for logging.
§Examples
- Logging to the global default logger.
use spdlog::prelude::*;
info!("logging to the default logger");
spdlog::default_logger().set_level_filter(LevelFilter::All);
trace!("logging to the default logger at trace level");
- Logging to a separated logger.
let separated_logger = /* ... */
info!(logger: separated_logger, "logging to a separated logger");
error!(logger: separated_logger, "logging to a separated logger at error level");
- Fork, configure and replace the default logger.
let new_logger = spdlog::default_logger().fork_with(|new_logger| {
// Configure the new logger...
Ok(())
})?;
spdlog::set_default_logger(new_logger);
info!("logging to the default logger, but it's reconfigured");
- For more examples, see ./examples directory.
Implementations§
Source§impl Logger
impl Logger
Sourcepub fn builder() -> LoggerBuilder
pub fn builder() -> LoggerBuilder
Gets a LoggerBuilder
with default parameters:
Parameter | Default Value |
---|---|
name | None |
sinks | [] |
level_filter | MoreSevereEqual(Info) |
flush_level_filter | Off |
flush_period | None |
error_handler | default error handler |
Sourcepub fn name(&self) -> Option<&str>
pub fn name(&self) -> Option<&str>
Gets the logger name.
Returns None
if the logger does not have a name.
Sourcepub fn set_name<S>(
&mut self,
name: Option<S>,
) -> StdResult<(), SetLoggerNameError>
pub fn set_name<S>( &mut self, name: Option<S>, ) -> StdResult<(), SetLoggerNameError>
Sets the logger name.
Sourcepub fn should_log(&self, level: Level) -> bool
pub fn should_log(&self, level: Level) -> bool
Determines if a log with the specified level would be logged.
This allows callers to avoid expensive computation of log arguments if the would be discarded anyway.
§Examples
use spdlog::prelude::*;
logger.set_level_filter(LevelFilter::MoreSevere(Level::Info));
assert_eq!(logger.should_log(Level::Debug), false);
assert_eq!(logger.should_log(Level::Info), false);
assert_eq!(logger.should_log(Level::Warn), true);
assert_eq!(logger.should_log(Level::Error), true);
logger.set_level_filter(LevelFilter::All);
assert_eq!(logger.should_log(Level::Debug), true);
assert_eq!(logger.should_log(Level::Info), true);
assert_eq!(logger.should_log(Level::Warn), true);
assert_eq!(logger.should_log(Level::Error), true);
Sourcepub fn flush(&self)
pub fn flush(&self)
Flushes sinks explicitly.
It calls Sink::flush
method internally for each sink in sequence.
Users can call this function to flush explicitly and/or use automatic
flushing policies. See also Logger::flush_level_filter
and
Logger::set_flush_period
.
Be aware that the method can be expensive, calling it frequently may affect performance.
Sourcepub fn flush_level_filter(&self) -> LevelFilter
pub fn flush_level_filter(&self) -> LevelFilter
Gets the flush level filter.
Sourcepub fn set_flush_level_filter(&self, level_filter: LevelFilter)
pub fn set_flush_level_filter(&self, level_filter: LevelFilter)
Sets a flush level filter.
When logging a new record, flush the buffer if this filter condition
returns true
.
This automatic flushing policy can work with
Logger::set_flush_period
at the same time.
§Examples
use spdlog::prelude::*;
logger.set_flush_level_filter(LevelFilter::Off);
trace!(logger: logger, "hello");
trace!(logger: logger, "world");
// Until here the buffer may not have been flushed (depending on sinks implementation)
logger.set_flush_level_filter(LevelFilter::All);
trace!(logger: logger, "hello"); // Logs and flushes the buffer once
trace!(logger: logger, "world"); // Logs and flushes the buffer once
Sourcepub fn level_filter(&self) -> LevelFilter
pub fn level_filter(&self) -> LevelFilter
Gets the log level filter.
Sourcepub fn set_level_filter(&self, level_filter: LevelFilter)
pub fn set_level_filter(&self, level_filter: LevelFilter)
Sourcepub fn set_flush_period(self: &Arc<Self>, interval: Option<Duration>)
pub fn set_flush_period(self: &Arc<Self>, interval: Option<Duration>)
Sets automatic periodic flushing.
This function receives a &Arc<Self>
. Calling it will spawn a new
thread internally.
This automatic flushing policy can work with
Logger::set_flush_level_filter
at the same time.
§Panics
-
Panics if
interval
is zero. -
Panics if this function is called with
Some
value and then clones theLogger
instead of theArc<Logger>
.
§Examples
use std::time::Duration;
// From now on, the `logger` will automatically call `flush` method the every 10 seconds.
logger.set_flush_period(Some(Duration::from_secs(10)));
// Disable automatic periodic flushing.
logger.set_flush_period(None);
Sourcepub fn set_error_handler(&self, handler: Option<ErrorHandler>)
pub fn set_error_handler(&self, handler: Option<ErrorHandler>)
Sets a error handler.
If an error occurs while logging or flushing, this handler will be
called. If no handler is set, the error will be print to stderr
and
then ignored.
§Examples
use spdlog::prelude::*;
spdlog::default_logger().set_error_handler(Some(|err| {
panic!("An error occurred in the default logger: {}", err)
}));
Sourcepub fn fork_with<F>(self: &Arc<Self>, modifier: F) -> Result<Arc<Self>>
pub fn fork_with<F>(self: &Arc<Self>, modifier: F) -> Result<Arc<Self>>
Forks and configures a separate new logger.
This function creates a new logger object that inherits logger
properties from Arc<Self>
. Then this function calls the given
modifier
function which configures the properties on the new
logger object. The created new logger object will be a separate
object from Arc<Self>
. (No ownership sharing)
§Examples
let old: Arc<Logger> = /* ... */
// Fork from an existing logger and add a new sink.
let new = old.fork_with(|new| {
new.sinks_mut().push(new_sink);
Ok(())
})?;
info!(logger: new, "this record will be written to `new_sink`");
info!(logger: old, "this record will not be written to `new_sink`");
Sourcepub fn fork_with_name<S>(
self: &Arc<Self>,
new_name: Option<S>,
) -> Result<Arc<Self>>
pub fn fork_with_name<S>( self: &Arc<Self>, new_name: Option<S>, ) -> Result<Arc<Self>>
Forks a separates new logger with a new name.
This function creates a new logger object that inherits logger
properties from Arc<Self>
and rename the new logger object to the
given name. The created new logger object will be a separate object
from Arc<Self>
. (No ownership sharing)
This is a shorthand wrapper for Logger::fork_with
.
§Examples
let old = Arc::new(Logger::builder().name("dog").build()?);
let new = old.fork_with_name(Some("cat"))?;
assert_eq!(old.name(), Some("dog"));
assert_eq!(new.name(), Some("cat"));
Trait Implementations§
Source§impl Clone for Logger
impl Clone for Logger
Source§fn clone(&self) -> Self
fn clone(&self) -> Self
Clones the Logger
.
§Panics
Panics if Logger::set_flush_period
is called with Some
value and
then clones the Logger
instead of the Arc<Logger>
.
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more