easy_ga/
logger.rs

1//! This module contains the implementation for verbosity debugging in the library.
2
3use cpu_time::ProcessTime;
4use std::fs::File;
5use std::fs::OpenOptions;
6use std::io::Write;
7use std::path::Path;
8use uuid::Uuid;
9
10static mut LEVEL: VerbosityLevel = VerbosityLevel::DISABLED;
11static mut TYPE: VerbosityType = VerbosityType::LOG_AND_SAVE;
12const PATH: &str = "target/easy_ga/logs/";
13
14lazy_static! {
15    static ref UUID: String = Uuid::new_v4().to_string();
16}
17
18/// Enumeration for the different levels of verbosity.
19#[derive(Debug, PartialEq, PartialOrd)]
20pub enum VerbosityLevel {
21    DISABLED = 0,
22    LOW = 1,
23    MID = 2,
24    HIGH = 3,
25}
26
27#[allow(non_camel_case_types)]
28pub enum VerbosityType {
29    LOG = 0,
30    SAVE = 1,
31    LOG_AND_SAVE = 2,
32}
33
34/// Sets de verbosity level.
35#[allow(non_snake_case)]
36pub fn LOG_verbosity(verbosity: VerbosityLevel) {
37    // unsafe: Modification of static mutable variable.
38    unsafe {
39        LEVEL = verbosity;
40    }
41}
42
43/// Sets de verbosity type.
44#[allow(non_snake_case)]
45pub fn LOG_verbosity_type(verbosity_type: VerbosityType) {
46    // unsafe: Modification of static mutable variable.
47    unsafe {
48        TYPE = verbosity_type;
49    }
50}
51
52/// Prints the log.
53#[allow(non_snake_case)]
54pub fn LOG(verbosity: VerbosityLevel, text: &str) {
55    unsafe {
56        if LEVEL != VerbosityLevel::DISABLED && verbosity != VerbosityLevel::DISABLED {
57            let now = ProcessTime::now();
58            // Format: MS |VerbosityLevel| Text
59            let message = format!("{:?} |{:?}| {text}", now.as_duration(), verbosity);
60            if verbosity <= LEVEL {
61                match TYPE {
62                    VerbosityType::LOG => {
63                        print(&message);
64                    }
65                    VerbosityType::SAVE => {
66                        save(&message);
67                    }
68                    VerbosityType::LOG_AND_SAVE => {
69                        print(&message);
70                        save(&message);
71                    }
72                }
73            }
74        }
75    }
76}
77
78/// Prints the LOG.
79fn print(text: &str) {
80    println!("{text}");
81}
82
83/// Saves the LOG.
84#[allow(unused_assignments)]
85fn save(text: &str) {
86    let mut file: File;
87    let full_path = format!("{PATH}easy_ga-{}.log", *UUID);
88    let path = std::path::Path::new(&full_path);
89    if !Path::exists(path) {
90        let prefix = path.parent().unwrap();
91        std::fs::create_dir_all(prefix).unwrap();
92        file = File::create(&full_path).unwrap();
93    }
94
95    file = OpenOptions::new()
96        .write(true)
97        .append(true)
98        .open(path)
99        .unwrap();
100
101    writeln!(file, "{text}").unwrap();
102}