Struct spdlog::Logger

source ·
pub struct Logger { /* private fields */ }
Expand description

A logger structure.

A logger contains a combination of sinks, and sinks implement writing log messages to actual targets.

Users usually log messages through log macros.

§Examples

use std::time::Duration;
use spdlog::prelude::*;

let default_logger: Arc<Logger> = spdlog::default_logger();
default_logger.set_level_filter(LevelFilter::All);
default_logger.set_flush_period(Some(Duration::from_secs(10)));
info!("logging with default logger");

custom_logger.set_level_filter(LevelFilter::All);
custom_logger.set_flush_period(Some(Duration::from_secs(10)));
info!(logger: custom_logger, "logging with custom logger");

For more examples, see ./examples directory.

Implementations§

source§

impl Logger

source

pub fn builder() -> LoggerBuilder

Constructs a LoggerBuilder.

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 message with the specified level would be logged.

This allows callers to avoid expensive computation of log message arguments if the message would be discarded anyway.

§Examples
use spdlog::prelude::*;

let logger: Arc<Logger> = spdlog::default_logger();

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<'_>)

Logs a record.

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

source

pub fn flush(&self)

Flushes any buffered records.

Users can call this function to flush manually or use auto-flush policies. See also Logger::flush_level_filter and Logger::set_flush_period.

Note that it is expensive, calling it frequently will 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 is true.

This auto-flush policy can work with Logger::set_flush_period together.

§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 filter level.

source

pub fn set_level_filter(&self, level_filter: LevelFilter)

Sets the log filter level.

§Examples

See Logger::should_log.

source

pub fn set_flush_period(self: &Arc<Self>, interval: Option<Duration>)

Sets periodic flush.

This function receives a &Arc<Self>. Calling it will spawn a new thread.

This auto-flush policy can work with Logger::set_flush_level_filter together.

§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, auto-flush the `logger` buffer every 10 seconds.
logger.set_flush_period(Some(Duration::from_secs(10)));

// Remove periodic auto-flush.
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: spdlog::Error| {
    panic!("spdlog-rs error: {}", err)
}));
source

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

Fork and configure 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: Arc<Logger> = old.fork_with(|new: &mut Logger| {
    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>,

Fork a separate 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<Logger> = Arc::new(Logger::builder().name("dog").build()?);
let new: Arc<Logger> = 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

Auto Trait Implementations§

§

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

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

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,

§

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>,

§

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>,

§

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.