Struct Logger

Source
pub struct Logger { /* private fields */ }
Expand description

The Logger struct used to print logs.

§Example

// Create a `Logger` with default configuration:
let mut logger = Logger::default();
logger.debug("debug message");
logger.info("info message");
logger.warning("warning message");
logger.error("error message");
logger.fatal("fatal error message");

Implementations§

Source§

impl Logger

Source

pub fn set_verbosity<I: Into<Verbosity>>(&mut self, verbosity: I)

Sets logger verbosity.

§Example
logger.set_verbosity(Verbosity::Quiet);
Source

pub fn toggle_log_filtering<I: Into<bool>>(&mut self, enabled: I)

Toggles log filtering.

  • true: logs will get filtered based on verbosity
  • false: log filtering will be disabled globally
Source

pub fn toggle_log_header_color<I: Into<bool>>(&mut self, enabled: I)

Toggles colored log headers.

  • true: Log headers will have colors
  • false: No colors :(
Source

pub fn set_debug_color<I: Into<Color>>(&mut self, color: I)

Sets debug log header color.

Source

pub fn set_info_color<I: Into<Color>>(&mut self, color: I)

Sets info log header color.

Source

pub fn set_warning_color<I: Into<Color>>(&mut self, color: I)

Sets warning header color.

Source

pub fn set_error_color<I: Into<Color>>(&mut self, color: I)

Sets error header color.

Source

pub fn set_fatal_color<I: Into<Color>>(&mut self, color: I)

Sets fatal error header color.

Source

pub fn set_debug_header(&mut self, header: &str)

Sets debug log header format.

Source

pub fn set_info_header(&mut self, header: &str)

Sets info log header format.

Source

pub fn set_warning_header(&mut self, header: &str)

Sets warning header format.

Source

pub fn set_error_header(&mut self, header: &str)

Sets error header format.

Source

pub fn set_fatal_header(&mut self, header: &str)

Sets fatal error header format.

Source

pub fn set_datetime_format(&mut self, format: &str)

Sets datetime format.

Source

pub fn set_log_format(&mut self, format: &str) -> Result<(), Error>

Sets the log format.

There are several placeholders in a log format string:

  • %c: Ascending log count starting at 1.
  • %d: The timestamp.
  • %h: The header indicating the log type (e.g., debug, error, etc.)
  • %m: The log message (this placeholder is mandatory, you will get an error if you don’t include this in your log format).

You can have multiple placeholders of the same type in a format string.

§Example
l.set_log_format("<l> <h>%h</h> <m>%m</m> </l>");
l.error("lorem ipsum");

Returns an error when the %m placeholder is missing.

Source

pub fn set_log_file_path(&mut self, path: &str) -> Result<(), Error>

Sets log file path.

Returns an error if the path is inaccessible.

Check out the File logging documentation.

§Example
// Set the log file path first:
logger.set_log_file_path(path);
// Then enable file logging:
logger.toggle_file_logging(true);
Source

pub fn toggle_file_logging<I: Into<bool>>( &mut self, enabled: I, ) -> Result<(), Error>

Toggles file logging.

Before enabling file logging, ensure that the log file path is set. This is because this method checks if the log file is writable. If the log file path is not set, or the file is not writable, enabling file logging will result in an error.

§Example
// Set the log file path first:
logger.set_log_file_path(path);
// Then enable file logging:
logger.toggle_file_logging(true);
Source

pub fn set_max_log_buffer_size<I: Into<u32>>(&mut self, size: I)

Sets the maximum allowed size for the log buffer.

When the buffer exceeds its max size, it gets flushed automatically to the log file. When set to 0, automatic flushing is disabled and the buffer can only be flushed manually.

If a log file lock is active, the log buffer will not be flushed automatically, regardless of the size limit.

§Example
let mut logger = Logger::default();
logger.set_log_file_path(path);
logger.toggle_file_logging(true);

// Make `Logger` flush the log buffer every 16 logs:
logger.set_max_log_buffer_size(16 as u32);

let mut i = 0;
loop {
    logger.info("Yay!");
    i += 1;
    if i >= 16 {
        break;
    }
}
// Here the buffer gets flushed, after sixteenth iteration.
Source

pub fn toggle_log_file_lock<I: Into<bool>>(&mut self, enabled: I)

Log file lock can be used to prevent race conditions when there are multiple threads accessing the log file at the same time.

§WARNING: leaving this option on for a long period of time will

cause high memory usage!

  • true: When log file lock is enabled, logger won’t flush into the log file. Instead, it will wait until the lock is disabled. You will not loose any logs, they will be stored in the log buffer even when it exceeds its size limit.
  • false: Logger will write to the log file normally.
Source

pub fn set_on_drop_file_policy<I: Into<OnDropPolicy>>(&mut self, policy: I)

Sets Logger’s on drop log file policy.

§Example
logger.set_on_drop_file_policy(OnDropPolicy::IgnoreLogFileLock);
Source

pub fn toggle_console_output<I: Into<bool>>(&mut self, enabled: I)

Toggles printing logs to stdout.

  • true: Logs will be printed in your terminal’s stdout.
  • false: No log output in your terminal.
Source

pub fn toggle_custom_log_buffer<I: Into<bool>>(&mut self, enabled: I)

Toggles the usage of a custom log buffer.

  • true: Logs will be stored in a buffer inside Logger and can be cloned using the clone_log_buffer() method. Be aware that this will lead to high memory usage if turned on for a log period of time.
  • false: Logs will not be stored in a log buffer.
Source

pub fn clear_log_buffer(&mut self)

Clears the custom log buffer.

Source§

impl Logger

Source

pub fn from_template_str(template: &str) -> Result<Logger, Error>

Creates a Logger instance from a JSON template as string.

§Example
let pretty_json = serde_json::to_string_pretty(&Logger::default())
    .expect("Failed to serialize logger!");
let raw_json = serde_json::to_string(&Logger::default())
    .expect("Failed to serialize logger!");
assert_eq!(Logger::default(), Logger::from_template_str(&pretty_json)
    .expect("Failed to deserialize logger!"));
assert_eq!(Logger::default(), Logger::from_template_str(&raw_json)
    .expect("Failed to deserialize logger!"));
Source

pub fn from_template(path: &str) -> Result<Logger, Error>

Creates a Logger instance from a template file.

Automatically expands environment variables.

§Example
let mut logger = Logger::from_template(path);
Source

pub fn save_template(&self, path: &str) -> Result<(), Error>

Saves a Logger to template file.

Automatically expands environment variables.

§Example
let mut logger = Logger::default();
logger.save_template(path);
Source§

impl Logger

Source

pub fn log_buffer(&self) -> &Vec<LogStruct>

Returns a reference to the custom log buffer.

Source

pub fn log_count(&self) -> &u128

Returns the number of logs printed since the struct was instantiated.

Source§

impl Logger

Source

pub fn print_log(&mut self, log: &LogStruct)

Used to print a log from a LogStruct.

§Example:
logger.print_log(&LogStruct::error("&%$#@!"));
Source

pub fn format_log(&self, log: &LogStruct) -> String

Returns a log entry from a LogStruct based on current Logger configuration.

§Example:
let log_string = logger.format_log(&LogStruct::error("ZXJyb3IK"));
Source

pub fn flush(&mut self) -> Result<(), Error>

Flushes log buffer (if file logging is enabled and log file lock disabled, it writes the log buffer to a file).

Returns an error when there is an issue writing to a file or log file lock is enabled.

Source

pub fn debug(&mut self, message: &str)

Prints a debug message to stdout.

Source

pub fn debug_no_filtering(&mut self, message: &str)

Prints a debug message to stdout, bypasses filtering.

Source

pub fn info(&mut self, message: &str)

Prints an informational message to stdout.

Source

pub fn info_no_filtering(&mut self, message: &str)

Prints an informational message to stdout, bypasses filtering.

Source

pub fn warning(&mut self, message: &str)

Prints a warning to stdout.

Source

pub fn warning_no_filtering(&mut self, message: &str)

Prints a warning to stdout, bypasses filtering.

Source

pub fn error(&mut self, message: &str)

Prints an error to stderr.

Source

pub fn fatal(&mut self, message: &str)

Prints a fatal error to stderr.

Trait Implementations§

Source§

impl Clone for Logger

Source§

fn clone(&self) -> Logger

Returns a copy of the value. Read more
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
Source§

impl Default for Logger

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Logger

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Drop for Logger

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Hash for Logger

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Logger

Source§

fn cmp(&self, other: &Logger) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Logger

Source§

fn eq(&self, other: &Logger) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Logger

Source§

fn partial_cmp(&self, other: &Logger) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Logger

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Logger

Source§

impl StructuralPartialEq for Logger

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

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,