Struct Logger

Source
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.


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");

Implementations§

Source§

impl Logger

Source

pub fn builder() -> LoggerBuilder

Gets a LoggerBuilder with default parameters:

ParameterDefault Value
nameNone
sinks[]
level_filterMoreSevereEqual(Info)
flush_level_filterOff
flush_periodNone
error_handlerdefault error handler
Source

pub fn name(&self) -> Option<&str>

Gets the logger name.

Returns None if the logger does not have a name.

Source

pub fn set_name<S>( &mut self, name: Option<S>, ) -> StdResult<(), SetLoggerNameError>
where S: Into<String>,

Sets the logger name.

Source

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);
Source

pub fn log(&self, record: &Record<'_>)

Passes a log into sinks in sequence.

It calls Sink::log method internally for each sink in sequence.

§Note

Users usually do not use this function directly, use logging macros instead.

Source

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.

Source

pub fn flush_level_filter(&self) -> LevelFilter

Gets the flush level filter.

Source

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
Source

pub fn level_filter(&self) -> LevelFilter

Gets the log level filter.

Source

pub fn set_level_filter(&self, level_filter: LevelFilter)

Sets the log level filter.

§Examples

See Logger::should_log.

Source

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 the Logger instead of the Arc<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);
Source

pub fn sinks(&self) -> &[Arc<dyn Sink>]

Gets a reference to sinks in the logger.

Source

pub fn sinks_mut(&mut self) -> &mut Sinks

Gets a mutable reference to sinks in the logger.

Source

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)
}));
Source

pub fn fork_with<F>(self: &Arc<Self>, modifier: F) -> Result<Arc<Self>>
where F: FnOnce(&mut Logger) -> Result<()>,

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`");
Source

pub fn fork_with_name<S>( self: &Arc<Self>, new_name: Option<S>, ) -> Result<Arc<Self>>
where S: Into<String>,

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

Source§

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)

Performs copy-assignment from source. Read more
Source§

impl Debug for Logger

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !Freeze for Logger

§

impl !RefUnwindSafe for Logger

§

impl Send for Logger

§

impl Sync for Logger

§

impl Unpin for Logger

§

impl !UnwindSafe for Logger

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.