prettylogger/
config.rs

1//! Contains various types used to customize `Logger` behavior.
2
3/// Contains various types used to customize `Logger` behavior.
4/// If you are good with the default `Logger` preset, you probably don't need
5/// to use this module.
6
7use serde::{Serialize, Deserialize};
8use std::fmt;
9use std::fmt::{Display, Formatter};
10use chrono::{Local, DateTime};
11
12#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Debug, Default,
13    Serialize, Deserialize)]
14/// Used to set the verbosity of a logger.
15///
16/// # Example
17/// ```
18/// # use prettylogger::{Logger, config::Verbosity};
19/// # let mut logger = Logger::default();
20/// logger.set_verbosity(Verbosity::Quiet);
21/// ```
22pub enum Verbosity {
23    /// Don't filter any logs.
24    All = 0,
25    #[default]
26    /// Just filter debug logs.
27    Standard = 1,
28    /// Only let warnings and errors to be displayed.
29    Quiet = 2,
30    /// I'm not gonna explain this one
31    ErrorsOnly = 3,
32}
33
34#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default,
35    Serialize, Deserialize)]
36/// Defines the policy for handling log file flushing when a `Logger` is
37/// dropped.
38///
39/// The default policy is `DiscardLogBuffer`.
40pub enum OnDropPolicy {
41    /// Completely ignore log file lock and write to file anyway.
42    IgnoreLogFileLock,
43    #[default]
44    /// Don't write to the log file when lock is enabled.
45    DiscardLogBuffer,
46}
47
48
49#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default,
50    Serialize, Deserialize)]
51/// Represents different types of log messages.
52///
53/// This enum is used to categorize the severity or type of a log message.
54/// The variants correspond to different levels of logging, from debugging
55/// information to fatal errors.
56///
57/// The default variant is `Info`.
58pub enum LogType {
59    /// A debug log, used for detailed information during development.
60    Debug = 0,
61    #[default]
62    Info = 1,
63    Warning = 2,
64    Err = 3,
65    /// A critical error that leads to an unrecoverable state.
66    FatalError = 4,
67}
68
69#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
70/// Represents a single log entry.
71///
72/// Can be used to create custom log messages or storing logs in memory for
73/// later use.
74///
75/// # Example:
76/// ```
77/// # use prettylogger::{Logger, config::LogStruct};
78/// # let mut logger = Logger::default();
79/// // Get a formatted log message from a `LogStruct` instance:
80/// let log_string = logger.format_log(&LogStruct::error("Much bad!"));
81/// ```
82pub struct LogStruct {
83    /// The log message.
84    pub message: String,
85    /// The type of the log (e.g., `Debug`, `Error`, `Info`, etc.).
86    pub log_type: LogType,
87    /// The date and time at which the log was created.
88    pub datetime: DateTime<Local>,
89}
90
91impl LogStruct {
92    /// Returns a `LogStruct` with **debug** preset applied.
93    pub fn debug(message: &str) -> LogStruct {
94        LogStruct {
95            message: message.to_string(),
96            log_type: LogType::Debug,
97            datetime: Local::now(),
98        }
99    }
100
101    /// Returns a `LogStruct` with **info** preset applied.
102    pub fn info(message: &str) -> LogStruct {
103        LogStruct {
104            message: message.to_string(),
105            log_type: LogType::Info,
106            datetime: Local::now(),
107        }
108    }
109
110    /// Returns a `LogStruct` with **warning** preset applied.
111    pub fn warning(message: &str) -> LogStruct {
112        LogStruct {
113            message: message.to_string(),
114            log_type: LogType::Warning,
115            datetime: Local::now(),
116        }
117    }
118
119    /// Returns a `LogStruct` with **error** preset applied.
120    pub fn error(message: &str) -> LogStruct {
121        LogStruct {
122            message: message.to_string(),
123            log_type: LogType::Err,
124            datetime: Local::now(),
125        }
126    }
127
128    /// Returns a `LogStruct` with **fatal error** preset applied.
129    pub fn fatal_error(message: &str) -> LogStruct {
130        LogStruct {
131            message: message.to_string(),
132            log_type: LogType::FatalError,
133            datetime: Local::now(),
134        }
135    }
136}
137
138impl Display for LogStruct {
139    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
140        write!(
141            f,
142            "Log: {}\nType: {:?}\nDateTime: {}",
143            self.message,
144            self.log_type,
145            self.datetime
146        )
147    }
148}
149
150
151impl fmt::Display for Verbosity {
152    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
153        let level_str = match *self {
154            Verbosity::All => "All",
155            Verbosity::Standard => "Standard",
156            Verbosity::Quiet => "Quiet",
157            Verbosity::ErrorsOnly => "ErrorsOnly",
158        };
159        write!(f, "{}", level_str)
160    }
161}
162
163impl TryFrom<i32> for Verbosity {
164    type Error = &'static str;
165    fn try_from(value: i32) -> Result<Self, Self::Error> {
166        match value {
167            0 => Ok(Verbosity::All),
168            1 => Ok(Verbosity::Standard),
169            2 => Ok(Verbosity::Quiet),
170            3 => Ok(Verbosity::ErrorsOnly),
171            _ => Err("Invalid value! Please provide a value in range 0-9."),
172        }
173    }
174}
175
176impl AsRef<str> for Verbosity {
177    fn as_ref(&self) -> &str {
178        match self {
179            Verbosity::All => "All",
180            Verbosity::Standard => "Standard",
181            Verbosity::Quiet => "Quiet",
182            Verbosity::ErrorsOnly => "ErrorsOnly",
183        }
184    }
185}
186
187
188impl Display for OnDropPolicy {
189    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
190        let level_str = match *self {
191            OnDropPolicy::IgnoreLogFileLock => "IgnoreLogFileLock",
192            OnDropPolicy::DiscardLogBuffer => "DiscardLogBuffer",
193        };
194        write!(f, "{}", level_str)
195    }
196}
197
198
199impl TryFrom<i32> for LogType {
200    type Error = &'static str;
201    fn try_from(value: i32) -> Result<Self, Self::Error> {
202        match value {
203            0 => Ok(LogType::Debug),
204            1 => Ok(LogType::Info),
205            2 => Ok(LogType::Warning),
206            3 => Ok(LogType::Err),
207            4 => Ok(LogType::FatalError),
208            _ => Err("Invalid value! Please provide a value in range 0-9."),
209        }
210    }
211}
212
213impl Display for LogType {
214    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
215        let level_str = match *self {
216            LogType::Debug => "Debug",
217            LogType::Info => "Info",
218            LogType::Warning => "Warning",
219            LogType::Err => "Error",
220            LogType::FatalError => "FatalError",
221        };
222        write!(f, "{}", level_str)
223    }
224}
225
226impl AsRef<str> for LogType {
227    fn as_ref(&self) -> &str {
228        match self {
229            LogType::Debug => "Debug",
230            LogType::Info => "Info",
231            LogType::Warning => "Warning",
232            LogType::Err => "Err",
233            LogType::FatalError => "Fatal Error",
234        }
235    }
236}