prettylogger/
config.rs

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