ultimate_logger 1.0.4

A simple logger for Rust
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Ultimate Logger is a simple logger that can write to a file and/or the console.
//!
//! # Examples
//!
//! ## Write to the console
//!
//! ```
//! use ultimate_logger::Logger;
//! use ultimate_logger::log_level::LogLevel;
//!
//! let mut logger = Logger::new(String::from("example"), LogLevel::Trace);
//!
//! logger.trace("This is a trace message");
//! logger.debug("This is a debug message");
//! logger.info("This is an info message");
//! logger.warning("This is a warning message");
//! logger.error("This is an error message");
//! logger.critical("This is a critical message");
//! ```
//!
//! This will output the following to the console with appropriate colors:
//!
//! ```text
//! [2020-05-01 12:00:00.000] [example] [trace] This is a trace message
//! [2020-05-01 12:00:00.000] [example] [debug] This is a debug message
//! [2020-05-01 12:00:00.000] [example] [info] This is an info message
//! [2020-05-01 12:00:00.000] [example] [warning] This is a warning message
//! [2020-05-01 12:00:00.000] [example] [error] This is an error message
//! [2020-05-01 12:00:00.000] [example] [critical] This is a critical message
//! ```
//!
//! ## Write to a file
//!
//! ```
//! use ultimate_logger::Logger;
//! use ultimate_logger::log_level::LogLevel;
//!
//! let mut logger = Logger::new_to_file(String::from("example"), LogLevel::Trace, String::from("log.txt"), true);
//!
//! logger.trace("This is a trace message");
//! logger.debug("This is a debug message");
//! logger.info("This is an info message");
//! logger.warning("This is a warning message");
//! logger.error("This is an error message");
//! logger.critical("This is a critical message");
//! ```
//!
//! Below is the text which will output to the file `log.txt`, and to the console. The console output will be colored.
//! ```text
//! [2020-05-01 12:00:00.000] [example] [trace] This is a trace message
//! [2020-05-01 12:00:00.000] [example] [debug] This is a debug message
//! [2020-05-01 12:00:00.000] [example] [info] This is an info message
//! [2020-05-01 12:00:00.000] [example] [warning] This is a warning message
//! [2020-05-01 12:00:00.000] [example] [error] This is an error message
//! [2020-05-01 12:00:00.000] [example] [critical] This is a critical message
//! ```
//!
//! # Features
//!
//! - Write to a file
//! - Write to the console
//! - Write to both
//! - Set a minimum log level
//! - Colored output
//! - Timestamps
//! - Multiple loggers with different names

mod log_file;
pub mod log_level;

use chrono::offset;
use colored::ColoredString;
use log_file::LogFile;

/// A logger that can write to a file and/or the console.
pub struct Logger {
    name: String,
    min_level: log_level::LogLevel,
    log_file: Option<log_file::LogFile>,
    write_to_console: bool,
    write_to_file: bool,
}

impl Logger {
    /// Creates a new logger that writes to the console.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the logger.
    /// * `min_level` - The minimum log level.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    /// use ultimate_logger::log_level::LogLevel;
    ///
    /// let mut logger = Logger::new(String::from("example"), LogLevel::Warning);
    /// ```
    ///
    /// This will create a logger that writes to the console and has the name "example" and the minimum log level "Warning".
    pub fn new(name: String, min_level: log_level::LogLevel) -> Self {
        Self {
            name,
            min_level,
            log_file: None,
            write_to_console: true,
            write_to_file: false,
        }
    }

    /// Creates a new logger that writes to a file.
    /// If `write_to_console_too` is set to `true`, the logger will also write to the console.
    /// If `write_to_console_too` is set to `false`, the logger will only write to the file.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the logger.
    /// * `min_level` - The minimum log level.
    /// * `filepath` - The path to the file. If the file doesn't exist, it will be created.
    /// * `write_to_console_too` - Whether the logger should write to the console too.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    /// use ultimate_logger::log_level::LogLevel;
    ///
    /// let logger = Logger::new_to_file(String::from("example"), LogLevel::Warning, String::from("log.txt"), true);
    /// ```
    ///
    /// This will create a logger that writes to the file "log.txt" and has the name "example" and the minimum log level "Warning".
    /// It will also write to the console, because `write_to_console_too` is set to `true`.
    ///
    /// # Panics
    ///
    /// This function will panic if the file can't be created or opened.
    /// This can happen if:
    /// - The file is already open in another process.
    /// - The file is a directory.
    /// - The file is read-only.
    /// - The file doesn't exist and the parent directory is read-only.
    /// - The file doesn't exist and the parent directory doesn't exist.
    /// - The file doesn't exist and the parent directory is a file.
    /// - The file doesn't exist and the parent directory is a symlink.
    /// - ...
    pub fn new_to_file(
        name: String,
        min_level: log_level::LogLevel,
        filepath: String,
        write_to_console_too: bool,
    ) -> Self {
        let log_file = log_file::LogFile::new(&filepath);

        Self {
            name,
            min_level,
            log_file: Some(log_file),
            write_to_console: write_to_console_too,
            write_to_file: true,
        }
    }

    /// Creates a new logger that writes to the console. The minimum log level is set to "Trace".
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the logger.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    ///
    /// let mut logger = Logger::new_default(String::from("example"));
    /// ```
    ///
    /// This will create a logger that writes to the console, has the name "example" and the minimum log level "Trace".
    pub fn new_default(name: String) -> Self {
        Self::new(name, log_level::LogLevel::Trace)
    }

    fn get_date_time() -> String {
        offset::Local::now().format("%F %T%.3f").to_string()
    }

    fn get_colored_level_name(level: log_level::LogLevel) -> ColoredString {
        level.color_string(level.to_string())
    }

    fn get_colored_message(level: log_level::LogLevel, message: &str) -> ColoredString {
        level.color_string(message)
    }

    fn log_to_file(log_file: &mut LogFile, level: log_level::LogLevel, message: &str, name: &str) {
        log_file.write(&format!(
            "[{}] [{}] [{}] {}\n",
            Logger::get_date_time(),
            name,
            level.to_string(),
            message
        ));
    }

    fn log_to_console(level: log_level::LogLevel, message: &str, name: &str) {
        println!(
            "[{}] [{}] [{}] {}",
            Logger::get_date_time(),
            name,
            Logger::get_colored_level_name(level),
            Logger::get_colored_message(level, message)
        );
    }

    /// Logs a message with the specified log level.
    /// Returns `true` if the message was logged and `false` if the message wasn't logged because the log level was too low.
    ///
    /// # Arguments
    ///
    /// * `level` - The log level of the message.
    /// * `message` - The message.
    ///
    /// # Examples
    ///
    /// ## Default log level
    ///
    /// ```
    /// use ultimate_logger::Logger;
    /// use ultimate_logger::log_level::LogLevel;
    ///
    /// let mut logger = Logger::new_default(String::from("example"));
    ///
    /// logger.log(LogLevel::Trace, "This is a trace message.");
    /// logger.log(LogLevel::Debug, "This is a debug message.");
    /// logger.log(LogLevel::Info, "This is an info message.");
    /// ```
    ///
    /// This will log the following messages:
    /// [2020-12-31 23:59:59.999] [example] [trace] This is a trace message.
    /// [2020-12-31 23:59:59.999] [example] [debug] This is a debug message.
    /// [2020-12-31 23:59:59.999] [example] [info] This is an info message.
    ///
    /// All messages will be logged, because the minimum log level is the default "Trace".
    ///
    /// ## Custom log level
    /// ```
    /// use ultimate_logger::Logger;
    /// use ultimate_logger::log_level::LogLevel;
    ///
    /// let mut logger = Logger::new(String::from("example"), LogLevel::Debug);
    ///
    /// logger.log(LogLevel::Trace, "This is a trace message.");
    /// logger.log(LogLevel::Debug, "This is a debug message.");
    /// logger.log(LogLevel::Info, "This is an info message.");
    /// ```
    ///
    /// This will log the following messages:
    /// [2020-12-31 23:59:59.999] [example] [debug] This is a debug message.
    /// [2020-12-31 23:59:59.999] [example] [info] This is an info message.
    ///
    /// Only the messages with the log level "Debug" and "Info" will be logged, because the minimum log level is "Debug".
    ///
    /// # Panics
    ///
    /// This function will panic if we try to log to a file and we can't write to the file.
    pub fn log(&mut self, level: log_level::LogLevel, message: &str) -> bool {
        if level as u8 >= self.min_level as u8 {
            if self.write_to_file {
                if let Some(log_file) = &mut self.log_file {
                    Logger::log_to_file(log_file, level, message, &self.name);
                }
            }

            if self.write_to_console {
                Logger::log_to_console(level, message, &self.name);
            }

            return true;
        }

        false
    }

    /// Logs a message with the log level "Trace".
    /// Returns `true` if the message was logged and `false` if the message wasn't logged because the log level was too low.
    /// This is a shortcut for [`log`](#method.log) with the log level "Trace".
    /// See [`log`](#method.log) for more information.
    ///
    /// The message will only be logged if the minimum log level is "Trace".
    /// This is the default minimum log level.
    ///
    /// # Arguments
    ///
    /// * `message` - The message.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    ///
    /// let mut logger = Logger::new_default(String::from("example"));
    ///
    /// logger.trace("This is a trace message.");
    /// ```
    ///
    /// This will log the following message:
    /// [2020-12-31 23:59:59.999] [example] [trace] This is a trace message.
    ///
    /// # Panics
    ///
    /// This function will panic if we try to log to a file and we can't write to the file.
    pub fn trace(&mut self, message: &str) -> bool {
        self.log(log_level::LogLevel::Trace, message)
    }

    /// Logs a message with the log level "Debug".
    /// Returns `true` if the message was logged and `false` if the message wasn't logged because the log level was too low.
    /// This is a shortcut for [`log`](#method.log) with the log level "Debug".
    /// See [`log`](#method.log) for more information.
    ///
    /// The message will only be logged if the minimum log level is "Trace" or "Debug".
    ///
    /// # Arguments
    ///
    /// * `message` - The message.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    ///
    /// let mut logger = Logger::new_default(String::from("example"));
    ///
    /// logger.debug("This is a debug message.");
    /// ```
    ///
    /// This will log the following message:
    /// [2020-12-31 23:59:59.999] [example] [debug] This is a debug message.
    ///
    /// # Panics
    ///
    /// This function will panic if we try to log to a file and we can't write to the file.
    pub fn debug(&mut self, message: &str) -> bool {
        self.log(log_level::LogLevel::Debug, message)
    }

    /// Logs a message with the log level "Info".
    /// Returns `true` if the message was logged and `false` if the message wasn't logged because the log level was too low.
    /// This is a shortcut for [`log`](#method.log) with the log level "Info".
    /// See [`log`](#method.log) for more information.
    ///
    /// The message will only be logged if the minimum log level is "Trace", "Debug" or "Info".
    ///
    /// # Arguments
    ///
    /// * `message` - The message.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    ///
    /// let mut logger = Logger::new_default(String::from("example"));
    ///
    /// logger.info("This is an info message.");
    /// ```
    ///
    /// This will log the following message:
    /// [2020-12-31 23:59:59.999] [example] [info] This is an info message.
    ///
    /// # Panics
    ///
    /// This function will panic if we try to log to a file and we can't write to the file.
    pub fn info(&mut self, message: &str) -> bool {
        self.log(log_level::LogLevel::Info, message)
    }

    /// Logs a message with the log level "Warning".
    /// Returns `true` if the message was logged and `false` if the message wasn't logged because the log level was too low.
    /// This is a shortcut for [`log`](#method.log) with the log level "Warning".
    /// See [`log`](#method.log) for more information.
    ///
    /// The message will only be logged if the minimum log level is "Trace", "Debug", "Info" or "Warning".
    ///
    /// # Arguments
    ///
    /// * `message` - The message.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    ///
    /// let mut logger = Logger::new_default(String::from("example"));
    ///
    /// logger.warning("This is a warning message.");
    /// ```
    ///
    /// This will log the following message:
    /// [2020-12-31 23:59:59.999] [example] [warning] This is a warning message.
    ///
    /// # Panics
    ///
    /// This function will panic if we try to log to a file and we can't write to the file.
    pub fn warning(&mut self, message: &str) -> bool {
        self.log(log_level::LogLevel::Warning, message)
    }

    /// Logs a message with the log level "Error".
    /// Returns `true` if the message was logged and `false` if the message wasn't logged because the log level was too low.
    /// This is a shortcut for [`log`](#method.log) with the log level "Error".
    /// See [`log`](#method.log) for more information.
    ///
    /// The message will only be logged if the minimum log level is "Trace", "Debug", "Info", "Warning" or "Error".
    ///
    /// # Arguments
    ///
    /// * `message` - The message.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    ///
    /// let mut logger = Logger::new_default(String::from("example"));
    ///
    /// logger.error("This is an error message.");
    /// ```
    ///
    /// This will log the following message:
    /// [2020-12-31 23:59:59.999] [example] [error] This is an error message.
    ///
    /// # Panics
    ///
    /// This function will panic if we try to log to a file and we can't write to the file.
    pub fn error(&mut self, message: &str) -> bool {
        self.log(log_level::LogLevel::Error, message)
    }

    /// Logs a message with the log level "Critical".
    /// Returns `true` if the message was logged and `false` if the message wasn't logged because the log level was too low.
    /// This is a shortcut for [`log`](#method.log) with the log level "Critical".
    /// See [`log`](#method.log) for more information.
    /// The message will always be logged, because this is the highest log level.
    ///
    /// # Arguments
    ///
    /// * `message` - The message.
    ///
    /// # Example
    ///
    /// ```
    /// use ultimate_logger::Logger;
    ///
    /// let mut logger = Logger::new_default(String::from("example"));
    ///
    /// logger.critical("This is a critical message.");
    /// ```
    ///
    /// This will log the following message:
    /// [2020-12-31 23:59:59.999] [example] [critical] This is a critical message.
    ///
    /// # Panics
    ///
    /// This function will panic if we try to log to a file and we can't write to the file.
    pub fn critical(&mut self, message: &str) -> bool {
        self.log(log_level::LogLevel::Critical, message)
    }
}

#[cfg(test)]
mod tests {
    use colored::Colorize;

    use super::*;

    // Logger::new()

    #[test]
    fn new_logger_should_have_correct_min_level() {
        let logger = Logger::new(String::from("test"), log_level::LogLevel::Warning);

        assert_eq!(logger.min_level, log_level::LogLevel::Warning);
    }

    #[test]
    fn new_logger_should_write_to_console() {
        let logger = Logger::new(String::from("test"), log_level::LogLevel::Warning);

        assert_eq!(logger.write_to_console, true);
    }

    #[test]
    fn new_logger_should_not_write_to_file() {
        let logger = Logger::new(String::from("test"), log_level::LogLevel::Warning);

        assert_eq!(logger.write_to_file, false);
    }

    // Logger::new_default()

    #[test]
    fn new_default_logger_should_have_level_trace() {
        let logger = Logger::new_default(String::from("test"));

        assert_eq!(logger.min_level, log_level::LogLevel::Trace);
    }

    // Logger::new_to_file()

    #[test]
    fn new_logger_to_file_should_enable_write_to_file() {
        let logger = Logger::new_to_file(
            String::from("test"),
            log_level::LogLevel::Warning,
            String::from("test.log"),
            false,
        );

        assert_eq!(logger.write_to_file, true);
    }

    #[test]
    fn new_logger_to_file_which_also_writes_to_console_should_enable_write_to_console() {
        let logger = Logger::new_to_file(
            String::from("test"),
            log_level::LogLevel::Warning,
            String::from("test.log"),
            true,
        );

        assert_eq!(logger.write_to_console, true);
    }

    #[test]
    fn new_logger_to_file_which_does_not_write_to_console_should_disable_write_to_console() {
        let logger = Logger::new_to_file(
            String::from("test"),
            log_level::LogLevel::Warning,
            String::from("test.log"),
            false,
        );

        assert_eq!(logger.write_to_console, false);
    }

    #[test]
    fn new_logger_to_file_should_have_correct_min_level() {
        let logger = Logger::new_to_file(
            String::from("test"),
            log_level::LogLevel::Warning,
            String::from("test.log"),
            false,
        );

        assert_eq!(logger.min_level, log_level::LogLevel::Warning);
    }

    // Logger::get_colored_level_name()

    #[test]
    fn get_colored_level_name_should_return_correct_string_for_critical() {
        let level_name = Logger::get_colored_level_name(log_level::LogLevel::Critical);

        assert_eq!(level_name, "critical".red().bold());
    }

    // Logger::get_colored_message()

    #[test]
    fn get_colored_message_should_return_correct_string_for_critical() {
        let message = Logger::get_colored_message(log_level::LogLevel::Critical, "test");

        assert_eq!(message, "test".red().bold());
    }

    // Logger::log()

    #[test]
    fn log_should_return_false_if_level_is_below_min_level() {
        let mut logger = Logger::new(String::from("test"), log_level::LogLevel::Error);

        let result = logger.log(log_level::LogLevel::Debug, "test");

        assert_eq!(result, false);
    }

    #[test]
    fn log_should_return_true_if_level_is_above_min_level() {
        let mut logger = Logger::new(String::from("test"), log_level::LogLevel::Debug);

        let result = logger.log(log_level::LogLevel::Error, "test");

        assert_eq!(result, true);
    }

    #[test]
    fn log_should_return_true_if_level_is_equal_to_min_level() {
        let mut logger = Logger::new(String::from("test"), log_level::LogLevel::Error);

        let result = logger.log(log_level::LogLevel::Error, "test");

        assert_eq!(result, true);
    }
}