windsh_core/logs.rs
1//! ## Logs
2//! There are parts of the application where the use or registration of logs
3//! is needed either to show them to the user graphically or to register
4//! them in session files.
5//!
6//! This is where the mod logs appears, which contains functions
7//! that will help us to do this job.
8
9use colored::*;
10
11/// these are possible levels for a log.
12/// we can use them as follows:
13/// ```rust
14/// use windsh_core::logs::LogLevel;
15///
16/// let log_level_error = LogLevel::Error;
17/// let log_level_warning = LogLevel::Warning;
18/// ```
19/// the functionality possible here is very basic,
20/// that is why it is usually used together with the `Log` structure
21#[derive(Debug)]
22pub enum LogLevel {
23 Info,
24 Ok,
25 Error,
26 Warning,
27}
28
29/// this is the structure that a log should have, this is global for any level
30/// we can use them as follows:
31/// ```rust
32/// use windsh_core::logs::{Log, LogLevel};
33///
34/// // this print a log
35/// Log::new(LogLevel::Warning, 0, "This is a test log.").show();
36///
37/// // this return a log
38/// let my_log: Log = Log::new(LogLevel::Warning, 0, "This is a test log.");
39///
40/// // we can also print an existing log
41/// my_log.show();
42/// ```
43/// these are some uses that this structure can be given.
44#[derive(Debug)]
45pub struct Log {
46 level: LogLevel,
47 code: u16,
48 message: String,
49}
50
51impl Log {
52 /// This function allows us to create a new log in a very intuitive and easy way,
53 /// it also allows us to do extra things like print it in the console
54 pub fn new(level: LogLevel, code: u16, message: &str) -> Self {
55 Self {
56 level,
57 code,
58 message: String::from(message),
59 }
60 }
61
62 pub fn show(&self) {
63 match self.level {
64 LogLevel::Info => {
65 println!("{} {}", "Info:".bold().green(), self.message);
66 }
67 LogLevel::Ok => {
68 println!("{} {}", "Ok:".bold().cyan(), self.message);
69 }
70 LogLevel::Error => {
71 println!("{} {}", "Error:".bold().red(), self.message);
72 }
73 LogLevel::Warning => {
74 println!("{} {}", "Warning:".bold().yellow(), self.message);
75 }
76 }
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn test_new_log() {
86 let log_new = Log::new(LogLevel::Error, 1, "message");
87
88 assert_eq!(log_new.code, 1);
89 assert_eq!(log_new.message, "message");
90 }
91}