rusty_logger/
modules.rs

1use crate::{logger::LogMessage, types::LogType};
2use chrono::Utc;
3use colored::{Color, Colorize};
4
5/// Trait that allows your struct to be implemented
6/// as a logger module
7///
8/// # Example
9///
10/// ```
11/// use rusty_logger::modules::Module;
12/// use rusty_logger::logger::LogMessage;
13///
14/// struct IncrementalModule {n: usize};
15///
16/// impl Module for IncrementalModule {
17///     fn print(&mut self, msg: &LogMessage) -> String {
18///         self.n = self.n + 1;
19///         (self.n - 1).to_string()
20///     }
21/// }
22/// ```
23pub trait Module {
24    fn print(&mut self, msg: &LogMessage) -> String;
25}
26
27/// A simple module to display the name of the logger
28pub struct Name;
29
30impl Module for Name {
31    fn print(&mut self, msg: &LogMessage) -> String {
32        if msg.options.colors {
33            format!("[{}]", msg.options.name.color(Color::Blue))
34        } else {
35            format!("[{}]", msg.options.name)
36        }
37    }
38}
39
40/// A simple module to display the type of the message
41pub struct Type;
42
43impl Module for Type {
44    fn print(&mut self, msg: &LogMessage) -> String {
45        let s = if msg.options.colors {
46            match msg.msg_type {
47                LogType::Error => "ERROR".color(Color::Red),
48                LogType::Warning => "WARN".color(Color::Yellow),
49                LogType::Info => "INFO".color(Color::Green),
50                LogType::Time => "TIME".color(Color::Cyan),
51            }
52            .to_string()
53        } else {
54            match msg.msg_type {
55                LogType::Error => "ERROR",
56                LogType::Warning => "WARN",
57                LogType::Info => "INFO",
58                LogType::Time => "TIME",
59            }
60            .to_string()
61        };
62        format!("[{}]", s)
63    }
64}
65
66/// A simple module to display the time of the log
67pub struct Time;
68
69impl Module for Time {
70    fn print(&mut self, msg: &LogMessage) -> String {
71        if msg.options.colors {
72            format!(
73                "[{}]",
74                Utc::now().format("%T").to_string().color(Color::Magenta)
75            )
76        } else {
77            format!("[{}]", Utc::now().format("%T").to_string())
78        }
79    }
80}