rusty-logger 0.3.0

A modular and simple logger for rust
Documentation
use crate::{logger::LogMessage, types::LogType};
use chrono::Utc;
use colored::{Color, Colorize};

/// Trait that allows your struct to be implemented
/// as a logger module
///
/// # Example
///
/// ```
/// use rusty_logger::modules::Module;
/// use rusty_logger::logger::LogMessage;
///
/// struct IncrementalModule {n: usize};
///
/// impl Module for IncrementalModule {
///     fn print(&mut self, msg: &LogMessage) -> String {
///         self.n = self.n + 1;
///         (self.n - 1).to_string()
///     }
/// }
/// ```
pub trait Module {
    fn print(&mut self, msg: &LogMessage) -> String;
}

/// A simple module to display the name of the logger
pub struct Name;

impl Module for Name {
    fn print(&mut self, msg: &LogMessage) -> String {
        if msg.options.colors {
            format!("[{}]", msg.options.name.color(Color::Blue))
        } else {
            format!("[{}]", msg.options.name)
        }
    }
}

/// A simple module to display the type of the message
pub struct Type;

impl Module for Type {
    fn print(&mut self, msg: &LogMessage) -> String {
        let s = if msg.options.colors {
            match msg.msg_type {
                LogType::Error => "ERROR".color(Color::Red),
                LogType::Warning => "WARN".color(Color::Yellow),
                LogType::Info => "INFO".color(Color::Green),
                LogType::Time => "TIME".color(Color::Cyan),
            }
            .to_string()
        } else {
            match msg.msg_type {
                LogType::Error => "ERROR",
                LogType::Warning => "WARN",
                LogType::Info => "INFO",
                LogType::Time => "TIME",
            }
            .to_string()
        };
        format!("[{}]", s)
    }
}

/// A simple module to display the time of the log
pub struct Time;

impl Module for Time {
    fn print(&mut self, msg: &LogMessage) -> String {
        if msg.options.colors {
            format!(
                "[{}]",
                Utc::now().format("%T").to_string().color(Color::Magenta)
            )
        } else {
            format!("[{}]", Utc::now().format("%T").to_string())
        }
    }
}