1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
//! # Logger utilities
//! A toolbox of small utilities to initialize and use loggers based on `simplelog` crate.
//! Useful for binaries that you need a terminal or a file logger fast.

use std::{fs::File, path::PathBuf, str::FromStr, sync::Mutex};

use chrono;
use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate};
use lazy_static::lazy_static;
use log::info;
use simplelog::*;

/// Initialize a terminal logger with the provided log level
pub fn terminal_logger_init(level: LevelFilter) {
    // Initialize the loggers
    let log_config = ConfigBuilder::new()
        .set_time_format("%d-%H:%M:%S%.3f".to_string())
        .set_time_to_local(true)
        .build();

    TermLogger::init(
        level,
        log_config.clone(),
        TerminalMode::Mixed,
        ColorChoice::Auto,
    )
    .unwrap();
}

// Initialize a terminal and a file logger with the provided log levels
pub fn combined_logger_init(
    terminal_level: LevelFilter,
    file_level: LevelFilter,
    log_path: &str,
    filename_prefix: &str,
) {
    let mut log_path = if log_path.is_empty() {
        std::env::temp_dir()
    } else {
        PathBuf::from_str(log_path).unwrap()
    };

    let instance_folder = format!("{}_{:?}", filename_prefix, chrono::offset::Utc::now());
    log_path.push(format!("{}-logs", filename_prefix));
    log_path.push(&instance_folder);
    log_path.push(format!("{}.log", filename_prefix));

    println!("[logger_init] Calculated log path [{:?}]", log_path);

    let log_config = ConfigBuilder::new()
        .set_time_format("%d-%H:%M:%S%.3f".to_string())
        .set_time_to_local(true)
        .build();
    CombinedLogger::init(vec![
        TermLogger::new(
            terminal_level,
            log_config.clone(),
            TerminalMode::Mixed,
            ColorChoice::Auto,
        ),
        WriteLogger::new(
            file_level,
            log_config,
            FileRotate::new(
                log_path.clone(),
                AppendCount::new(5),
                ContentLimit::Lines(30000),
                Compression::None,
                #[cfg(unix)]
                None,
            ),
        ),
    ])
    .unwrap();

    log::logger().enabled(&DUMMY);

    info!("[logger_init] Calculated log path [{:?}]", log_path);
}

lazy_static! {
    pub static ref DUMMY: log::Metadata<'static> = log::MetadataBuilder::new().build();

    /// Scanner Results File (Used for Demos)
    pub static ref RESULTS_FILE: Mutex<File> = {
        let mut log_path = std::env::temp_dir();
        log_path.push("scanner-results.log");

        Mutex::new(File::options()
            .append(true)
            .create(true)
            .open(log_path)
            .expect("Results File FAILED!"))
    };
}

pub enum LoggerPrintMode {
    Results,
    Info,
}

#[macro_export]
macro_rules! results_info {
    (mode:$mode:expr, $($arg:tt)+) => {{
        if $mode == "results" {
            $crate::results_info!($($arg)+);
        }
        else {
            $crate::results_info!(info, $($arg)+);
        }
    }};

    (info, $($arg:tt)+) => {{
        $crate::log_info!($($arg)+);
    }};

    ($($arg:tt)+) => {{
        use std::io::Write;
        use chrono::Local;

        $crate::log_info!($($arg)+);

        let timestamp = Local::now().format("%d-%H:%M:%S%.3f").to_string();
        let mut res_file = $crate::logger::RESULTS_FILE.lock().unwrap();
        writeln!(res_file,"{} {}",timestamp, format!($($arg)+)).unwrap();
    }};
}

#[macro_export]
macro_rules! log_info {
    ($($arg:tt)+) => {{
        if log::logger().enabled(&$crate::logger::DUMMY) {
            log::info!($($arg)+);
        }
        else {
            std::println!($($arg)+);
        }
    }};
}

#[macro_export]
macro_rules! log_warn {
    ($($arg:tt)+) => {{
        if log::logger().enabled(&$crate::logger::DUMMY) {
            log::warn!($($arg)+);
        }
        else {
            std::println!($($arg)+);
        }
    }};
}

#[macro_export]
macro_rules! log_debug {
    ($($arg:tt)+) => {{
        if log::logger().enabled(&$crate::logger::DUMMY) {
            log::debug!($($arg)+);
        }
        else {
            std::println!($($arg)+);
        }
    }};
}

#[macro_export]
macro_rules! log_trace {
    ($($arg:tt)+) => {{
        if log::logger().enabled(&$crate::logger::DUMMY) {
            log::trace!($($arg)+);
        }
        else {
            std::println!($($arg)+);
        }
    }};
}

#[macro_export]
macro_rules! log_error {
    ($($arg:tt)+) => {{
        if log::logger().enabled(&$crate::logger::DUMMY) {
            log::error!($($arg)+);
        }
        else {
            std::println!($($arg)+);
        }
    }};
}

#[cfg(test)]
mod tests {
    use crate::logger::*;

    #[test]
    fn logger_test() {
        log_info!("INFO Test TO PRINTLN!");
        log_debug!("DEBUG Test TO PRINTLN!");

        if !log::logger().enabled(&crate::logger::DUMMY) {
            terminal_logger_init(LevelFilter::Debug);
        }

        log_info!("INFO Test TO LOGGER!");
        log_debug!("DEBUG Test TO LOGGER!");
    }

    #[test]
    fn results_logger_test() {
        log_info!("INFO Test TO PRINTLN!");
        results_info!("RESULTS Test from PRINTLN!");

        if !log::logger().enabled(&crate::logger::DUMMY) {
            terminal_logger_init(LevelFilter::Debug);
        }

        log_info!("INFO Test TO LOGGER!");
        results_info!("RESULTS Test from LOGGER!");

        log_info!("INFO Test TO LOGGER!");
        results_info!(info, "{}", "RESULTS Test from LOGGER2!");
        results_info!("{}", "RESULTS Test from LOGGER3!");
        let a = "results";
        results_info!(mode: a, "{}", "TEST");
        let b = "info";
        results_info!(mode: b, "{}", "TEST2");
    }
}