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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#[cfg(test)]
mod tests {
    use crate::logger::*;

    #[test]
    fn log(){
        let mut logger = Logger::new("main", std::io::stderr());
        logger.options.time_unit = TimeUnit::Microseconds;
        let timer_name = "Small code block";
        logger.timer_start(timer_name);
        logger.info("Hello !");
        logger.warn("Oups !");
        logger.timer_log_and_reset(timer_name);
        logger.error("Oh no !");
        logger.timer_log_and_stop(timer_name);
    }
}

pub mod logger {
    use std::{
        collections::HashMap,
        fmt::Display,
        io::stderr,
        time::{
            SystemTime,
            Duration
        }};
    use colored::*;
    use chrono::Utc;

    pub struct Logger<T: std::io::Write> {
        name: String,
        pub options: Options<T>,
        timer: Timer
    }

    pub struct Colors {
        pub name: Color,
        pub info: Color,
        pub warn: Color,
        pub fail: Color,
        pub time: Color,
        pub timer: Color,
    }

    pub struct Options<T: std::io::Write> {
        pub time: bool,
        pub name: bool,
        pub time_unit: TimeUnit,
        pub colors: Option<Colors>,
        output: T
    }

    pub struct Timer {
        timers: HashMap<String, SystemTime>
    }

    pub enum LogType {
        Info,
        Warning,
        Error,
        Time
    }

    #[derive(Copy, Clone)]
    pub enum TimeUnit {
        Nanoseconds,
        Microseconds,
        Milliseconds
    }

    impl Colors {
        pub fn new() -> Colors {
            Colors {
                name: Color::Blue,
                info: Color::Green,
                warn: Color::Yellow,
                fail: Color::Red,
                time: Color::Magenta,
                timer: Color::Cyan,
            }
        }
    }

    impl<T: std::io::Write> Options<T> {
        pub fn new(stream: T) -> Options<T> {
            Options {
                time: false,
                name: true,
                time_unit: TimeUnit::Milliseconds,
                colors: Some(Colors::new()),
                output: stream
            }
        }
    }

    impl Timer {
        pub fn new() -> Timer {
            Timer {
                timers: HashMap::new()
            }
        }

        fn start(&mut self, msg: &str) {
            self.timers.insert(msg.to_string(), SystemTime::now());
        }

        fn get(&self, msg: &str) -> Option<Duration> {
            if let Some(time) = self.timers.get(msg) {
                Some(time.elapsed().unwrap_or(Duration::from_micros(0)))
            } else {
                None
            }
        }

        fn stop(&mut self, msg: &str) -> Option<Duration> {
            if let Some(time) = self.timers.remove(msg) {
                Some(time.elapsed().unwrap_or(Duration::from_micros(0)))
            } else {
                None
            }
        }

        fn reset(&mut self, msg: &str) -> Option<Duration> {
            if let Some(time) = self.timers.insert(msg.to_string(), SystemTime::now()) {
                Some(time.elapsed().unwrap_or(Duration::from_micros(0)))
            } else {
                None
            }
        }
    }

    impl<T: std::io::Write> Logger<T> {
        /// Creates a new Logger with default values and the given name
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::Logger;
        ///
        /// let mut logger = Logger::new("name", std::io::stdout());
        /// logger.info("This is a new logger named 'name' !");
        /// ```
        pub fn new(s: &str, output: T) -> Self {
            Logger {
                name: s.to_string(),
                options: Options::new(output),
                timer: Timer::new()
            }
        }

        /// Creates a new Logger with default values, custom options and the given name
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::{Logger, Options};
        ///
        /// let options = Options::new(std::io::stdout());
        /// let mut logger = Logger::with_options("name", options);
        /// logger.info("This is a new logger named 'name' which has 'options' as its options !");
        /// ```
        pub fn with_options(s: &str, options: Options<T>) -> Logger<T> {
            Logger {
                name: s.to_string(),
                options: options,
                timer: Timer::new()
            }
        }

        /// Formats the message with the current logger options
        /// and then prints it. It is a private function and is
        /// only used by the other functions (info, warn and
        /// error) to print the message.
        ///
        /// It goes through the options of the logger it is
        /// called on and formats the message accordingly.
        ///
        /// It is also responsible to print everything in
        /// the correct colors
        fn log<D: Display>(&mut self, msg: D, msg_type: LogType) {
            let mut output;

            if let Some(colors) = &self.options.colors {
                match msg_type {
                    LogType::Error => {
                        output = format!("[{}]", "FAIL".color(colors.fail));
                    },
                    LogType::Warning => {
                        output = format!("[{}]", "WARN".color(colors.warn));
                    },
                    LogType::Info => {
                        output = format!("[{}]", "INFO".color(colors.info));
                    },
                    LogType::Time => {
                        output = format!("[{}]", "TIME".color(colors.timer));
                    }
                };

                if self.options.time {
                    output = format!("{}[{}]", output, Utc::now().format("%T").to_string().color(colors.time));
                }

                if self.options.name {
                    output = format!("[{}]{}", self.name.color(colors.name), output);
                }
            } else {
                match msg_type {
                    LogType::Error => {
                        output = format!("[{}]", "FAIL");
                    },
                    LogType::Warning => {
                        output = format!("[{}]", "WARN");
                    },
                    LogType::Info => {
                        output = format!("[{}]", "INFO");
                    },
                    LogType::Time => {
                        output = format!("[{}]", "TIME");
                    }
                };

                if self.options.time {
                    output = format!("{}[{}]", output, Utc::now().format("%T").to_string());
                }

                if self.options.name {
                    output = format!("[{}]{}", self.name, output);
                }
            }


            match write!(self.options.output, "{}: {}\n", output, msg) {
                std::result::Result::Err(err) => {
                    Logger::static_log(err, LogType::Error, stderr())
                },
                std::result::Result::Ok(_) => {}
            }
        }

        /// Static implementation for the log function
        ///
        /// Mainly used to print internal error messages
        /// but can also be used by an end user
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::{Logger, LogType};
        ///
        /// Logger::static_log("Printing on the fly", LogType::Info, std::io::stdout());
        /// ```
        pub fn static_log<D: Display>(msg: D, msg_type: LogType, output: T) {
            let mut logger = Logger::new("STATIC", output);
            logger.log(msg, msg_type);
        }

        /// Logs the given message to the output
        /// as an information
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::{Logger, LogType};
        ///
        /// let mut logger = Logger::new("name", std::io::stdout());
        /// logger.info("Here is some information I want to log");
        /// ```
        pub fn info<D: Display>(&mut self, msg: D) {
            self.log(msg, LogType::Info);
        }

        /// Logs the given message to the output
        /// as a warning
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::{Logger, LogType};
        ///
        /// let mut logger = Logger::new("name", std::io::stdout());
        /// logger.warn("Here is a warning");
        pub fn warn<D: Display>(&mut self, msg: D) {
            self.log(msg, LogType::Warning);
        }

        /// Logs the given message to the output
        /// as an error
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::{Logger, LogType};
        ///
        /// let mut logger = Logger::new("name", std::io::stdout());
        /// logger.info("Some error happened");
        /// ```
        pub fn error<D: Display>(&mut self, msg: D) {
            self.log(msg, LogType::Error);
        }

        /// Starts a new timer with the given name
        /// and the actual time
        pub fn timer_start(&mut self, msg: &str) {
            self.timer.start(msg);
        }

        /// Gets the duration from when the timer
        /// with the given name was started
        pub fn timer_get(&self, msg: &str) -> Option<Duration> {
            self.timer.get(msg)
        }

        /// Stops the timer with the given name
        /// and returns it as a duration
        pub fn timer_stop(&mut self, msg: &str) -> Option<Duration> {
            self.timer.stop(msg)
        }

        /// Resets the timer with the given name
        /// and returns the duration of the timer
        /// before being reset as a duration
        pub fn timer_reset(&mut self, msg: &str) -> Option<Duration> {
            self.timer.reset(msg)
        }

        /// Logs the time elapsed between the
        /// start/reset of the timer and now
        /// **without** reseting it
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::{Logger, LogType};
        ///
        /// let mut logger = Logger::new("name", std::io::stdout());
        ///
        /// logger.timer_start("new_timer");
        ///
        /// std::thread::sleep(std::time::Duration::from_millis(1));
        ///
        /// logger.timer_log("new_timer");
        /// ```
        pub fn timer_log(&mut self, msg: &str) {
            if let Some(time) = self.timer.get(msg) {
                match self.options.time_unit {
                    TimeUnit::Nanoseconds => {
                        self.log(format!("{} - {}ns", msg, time.as_nanos()), LogType::Time);
                    },
                    TimeUnit::Microseconds => {
                        self.log(format!("{} - {}μs", msg, time.as_micros()), LogType::Time);
                    },
                    TimeUnit::Milliseconds => {
                        self.log(format!("{} - {}ms", msg, time.as_millis()), LogType::Time);
                    }
                }
            } else {
                Logger::static_log(msg, LogType::Error, stderr());
            }
        }

        /// Logs the time elapsed between the
        /// start/reset of the timer and now
        /// and then stops it
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::{Logger, LogType};
        ///
        /// let mut logger = Logger::new("name", std::io::stdout());
        ///
        /// logger.timer_start("new_timer");
        ///
        /// std::thread::sleep(std::time::Duration::from_millis(1));
        ///
        /// logger.timer_log_and_stop("new_timer");
        /// ```
        pub fn timer_log_and_stop(&mut self, msg: &str) {
            self.timer_log(msg);
            self.timer_stop(msg);
        }

        /// Logs the time elapsed between the
        /// start/reset of the timer and now
        /// and then resets it
        ///
        /// # Example
        ///
        /// ```
        /// use rusty_logger::logger::{Logger, LogType};
        ///
        /// let mut logger = Logger::new("name", std::io::stdout());
        ///
        /// logger.timer_start("new_timer");
        ///
        /// std::thread::sleep(std::time::Duration::from_millis(1));
        ///
        /// logger.timer_log_and_reset("new_timer");
        ///
        /// std::thread::sleep(std::time::Duration::from_millis(1));
        ///
        /// logger.timer_log_and_stop("new_timer");
        /// ```
        pub fn timer_log_and_reset(&mut self, msg: &str) {
            self.timer_log(msg);
            self.timer_reset(msg);
        }
    }
}