the_logger 0.5.3

A very simple but customizable 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
use std::fs;
use lazy_static::lazy_static;
use std::fs::File;
use std::io::Write;
use tokio::sync::RwLock;
use crate::logger::logger_config::{LogLevel, TheLoggerConfig};

lazy_static!(
    /// Static reference that allows the user to access the logger from anywhere in the code.
    static ref THE_LOGGER: TheLogger = TheLogger::new();
);

/// Main struct to instantiate when using TheLogger. Its inner RwLock allows only one usage of the file writer and
/// configuration member at a time.
pub struct TheLogger {
    inner: RwLock<TheLoggerInner>
}

#[doc(hidden)]
struct TheLoggerInner {
    config: TheLoggerConfig,
    file_writer: File
}



impl TheLogger {
    #[doc(hidden)]
    fn new() -> Self {
        fs::create_dir_all("./logs/").unwrap();
        Self {
            inner: RwLock::new(TheLoggerInner {
                config: TheLoggerConfig::default(),
                file_writer: std::fs::OpenOptions::new()
                                     .write(true)
                                     .create(true)
                                     .append(true)
                                     .open(
                                         format!("./logs/Log {}.log", chrono::Local::now().naive_local().format("%Y-%m-%d"))
                                     ).unwrap()
            })
        }
    }

    /// ## Description
    /// Returns the instance of the logger. This is the main way to access the logger, and it'll be configured by default.
    ///
    /// TheLogger has built-in support for the format! macro, so the user can use it to format the log message without
    /// having to allocate an extra variable, as shown in the example below.
    ///
    /// Its setup can be changed later using the methods provided by this crate.
    ///
    /// ### Default settings:
    /// - All date elements enabled
    /// - All time elements enabled
    /// - Log level enabled and set to VERBOSE
    /// - Time format set to Local time
    /// - File name and line number shown, but column number is hidden.
    /// - File name, location, column information section is limited to a maximum default of 60 chars, configurable.
    /// - Log content is limited to a maximum default of 300 chars, also configurable.
    ///
    /// ### Log Example
    /// ```text
    /// 2023-12-16 17:08:07.451851800  [VERBOSE]  This is a log example for the the_logger crate
    /// ```
    ///
    /// ### Usage example
    /// ````rust
    /// use the_logger::{log_warning, TheLogger};
    ///
    /// async fn init_logger(thread_id: u8) {
    ///     let logger: &TheLogger = TheLogger::instance();
    ///     log_warning!(logger, "This is a warning emitted by thread {}", thread_id);
    /// }
    /// ````
    pub fn instance() -> &'static Self {
        &THE_LOGGER
    }

    /// ## Description
    /// Executes the logging to the file according to the current configuration
    pub async fn log_in_file(&self, (file, line, column): (&str, u32, u32), incoming_msg: &str) {
        let mut msg = String::new();
        let mut location_info = String::new();
        let location_length;
        let content_length;

        {
            let inner = self.inner.read().await;

            //  Datetime formatting
            let datetime = if inner.config.get_utc_config() {
                chrono::Utc::now().naive_utc()
            } else {
                chrono::Local::now().naive_local()
            };
            let mut datetime_format = String::new();

            //  Date formatting
            let mut space_date_time = false;
            let mut time_shown = false;
            if !inner.config.get_years_config() {
                datetime_format.push_str("%Y");
                space_date_time = true;
            }
            if !inner.config.get_months_config() {
                space_date_time = true;
                datetime_format.push_str("-%m");
            }
            if !inner.config.get_days_config() {
                space_date_time = true;
                datetime_format.push_str("-%d");
            }
            if space_date_time {
                datetime_format.push(' ');
            }

            //  Time formatting
            if !inner.config.get_hours_config() {
                datetime_format.push_str("%H");
                time_shown = true;
            }
            if !inner.config.get_minutes_config() {
                datetime_format.push_str(":%M");
                time_shown = true;
            }
            if !inner.config.get_seconds_config() {
                datetime_format.push_str(":%S");
                time_shown = true;
            }
            match (inner.config.get_millisecs_config(), inner.config.get_microsecs_config()) {
                (false, false) => {
                    datetime_format.push_str(".%6f");
                    time_shown = true;
                },
                (false, true) => {
                    datetime_format.push_str(".%3f");
                    time_shown = true;
                },
                (true, false) => {},
                _ => {}
            }
            if space_date_time || time_shown {
                datetime_format.push('\t');
            }
            msg.push_str(&datetime.format(&datetime_format).to_string());

            //  Log level type config
            if !inner.config.get_level_config() {
                match inner.config.get_log_level() {
                    LogLevel::Verbose => {
                        msg.push_str("[VERBOSE]\t");
                    },
                    LogLevel::Information => {
                        msg.push_str("[INFO]\t\t");
                    },
                    LogLevel::Error => {
                        msg.push_str("[ERROR]\t\t");
                    },
                    LogLevel::Warning => {
                        msg.push_str("[WARNING]\t");
                    },
                    LogLevel::Debug => {
                        msg.push_str("[DEBUG]\t\t");
                    },
                    LogLevel::Trace => {
                        msg.push_str("[TRACE]\t\t");
                    },
                    LogLevel::Critical => {
                        msg.push_str("[CRITICAL]\t");
                    }
                }
                //  Only insert tab if location data is not shown
            } else if !inner.config.get_file_name_config() || !inner.config.get_file_line_config() || inner.config.get_file_column_config() {
                msg.push('\t');
            }

            //  File location configuration
            if !inner.config.get_file_name_config() {
                location_info.push_str(format!("@{}", file).as_str());

                if !inner.config.get_file_line_config() {
                    location_info.push_str(format!(": {}", line).as_str());

                    if inner.config.get_file_column_config() {
                        location_info.push_str(format!("|{}", column).as_str());
                    }
                }
            }

            //  Location info and content lengths configuration
            location_length = inner.config.get_location_length();
            content_length = inner.config.get_log_content_length();
        }

        //  Close the message string and log it. Trim the message if it's longer than the configured lengths
        if location_length < location_info.len() {
            location_info = location_info.as_str()[0..location_length].to_string();
            //  Append a tab to separate the location info and the content a little bit
            location_info.push_str("\t\t");
        }
        if !location_info.is_empty() {
            msg.push_str(format!("{:<location_length$}", location_info).as_str());
        }
        if content_length < incoming_msg.len() {
            msg.push_str(incoming_msg[0..content_length].as_ref());
        } else {
            msg.push_str(incoming_msg);
        }
        self.inner.write().await.file_writer.write_all(format!("{}\n", msg).as_bytes()).unwrap();
    }

    /// ## Description
    /// Allows the user to configure the logger using a single config call. The configuration must previously be created
    /// by instantiating the TheLoggerConfig struct adn setting each desired field with its builder methods.
    ///
    /// Every change to the configuration is made through this method.
    ///
    /// ### Initial configuration example
    /// ```rust
    /// use the_logger::{TheLogger, TheLoggerConfig};
    ///
    /// async fn init_logger() {
    ///     let logger_config = TheLoggerConfig::default()
    ///         .hide_file_line()
    ///         .hide_microsecs()
    ///         .hide_level();
    ///
    ///     let logger: &TheLogger = TheLogger::instance().config(logger_config).await;
    /// }
    /// ```
    ///
    /// As a result, the user has configured the logger to hide the file line number, the microsecs and the log level,
    ///
    /// and leave the rest of the parameters with their default values.
    ///
    /// ### Modifying configuration example
    /// If the user needs to modify the logger configuration for any particular reason, for example for a specific
    ///
    /// routine that doesn't need to show all the data or needs to show different data, this can be achieved in a similar
    ///
    /// way to the initial configuration:
    ///
    /// ```rust
    /// use the_logger::{TheLogger, TheLoggerConfig};
    ///
    /// async fn config_logger() {
    ///     let logger_config = TheLoggerConfig::default()
    ///         .show_file_line()
    ///         .show_microsecs()
    ///         .show_level();
    ///
    ///     let logger: &TheLogger = TheLogger::instance().config(logger_config).await;
    /// }
    /// ```
    ///
    /// As opposed to the previous example, we're now reverting the changes made to the logger configuration, so that
    ///
    /// the file line number, microseconds stamp and log level are shown.
    pub async fn config(&self, logger_config: TheLoggerConfig) -> &Self {
        self.inner.write().await.config = logger_config;
        self
    }

    //////////////////////
    /* Log Type methods */
    //////////////////////
    /// ## Description
    /// Configures the log level as verbose adding the [[VERBOSE]] tag
    pub async fn verbose(&self) -> &Self {
        self.inner.write().await.config.set_log_level(LogLevel::Verbose);
        self
    }

    /// ## Description
    /// Configures the log level as informational adding the [[INFO]] tag
    pub async fn info(&self) -> &Self {
        self.inner.write().await.config.set_log_level(LogLevel::Information);
        self
    }

    /// ## Description
    /// Configures the log level as error adding the [[ERROR]] tag
    pub async fn error(&self) -> &Self{
        self.inner.write().await.config.set_log_level(LogLevel::Error);
        self
    }

    /// ## Description
    /// Configures the log level as warning adding the [[WARNING]] tag
    pub async fn warning(&self) -> &Self {
        self.inner.write().await.config.set_log_level(LogLevel::Warning);
        self
    }

    /// ## Description
    /// Configures the log level as debug adding the [[DEBUG]] tag
    pub async fn debug(&self) -> &Self {
        self.inner.write().await.config.set_log_level(LogLevel::Debug);
        self
    }

    /// ## Description
    /// Configures the log level as trace adding the [[TRACE]] tag
    pub async fn trace(&self) -> &Self {
        self.inner.write().await.config.set_log_level(LogLevel::Trace);
        self
    }

    /// ## Description
    /// Configures the log level as critical adding the [[CRITICAL]] tag
    pub async fn critical(&self) -> &Self {
        self.inner.write().await.config.set_log_level(LogLevel::Critical);
        self
    }

    ///////////////////////////
    /* Configuration methods */
    ///////////////////////////
    /* Hide methods */
    //////////////////
    /// ## Description
    /// Configures the log date to hide the years. Default is to show them
    pub async fn hide_years(&self) -> &Self {
        self.inner.write().await.config.set_years_config(true);
        self
    }

    /// ## Description
    /// Configures the log date to hide the months. Default is to show them
    pub async fn hide_months(&self) -> &Self {
        self.inner.write().await.config.set_months_config(true);
        self
    }

    /// ## Description
    /// Configures the log date to hide the days. Default is to show them
    pub async fn hide_days(&self) -> &Self {
        self.inner.write().await.config.set_days_config(true);
        self
    }

    /// ## Description
    /// Configures the log time to hide the hours. Default is to show them
    pub async fn hide_hours(&self) -> &Self {
        self.inner.write().await.config.set_hours_config(true);
        self
    }

    /// ## Description
    /// Configures the log time to hide the minutes. Default is to show them
    pub async fn hide_minutes(&self) -> &Self {
        self.inner.write().await.config.set_minutes_config(true);
        self
    }

    /// ## Description
    /// Configures the log time to hide the seconds. Default is to show them
    pub async fn hide_seconds(&self) -> &Self {
        self.inner.write().await.config.set_seconds_config(true);
        self
    }

    /// ## Description
    /// Configures the log time to hide the milliseconds. Default is to show them
    ///
    /// ### Warning
    /// Hiding the milliseconds and showing the microseconds would cause an unexpected time tracking in the logs,
    ///
    /// therefore, in this specific case, both milliseconds and microseconds will be hidden
    pub async fn hide_millisecs(&self) -> &Self {
        self.inner.write().await.config.set_millisecs_config(true);
        self
    }

    /// ## Description
    /// Configures the log time to hide the microseconds. Default is to show them
    ///
    /// ### Warning
    /// Hiding the milliseconds and showing the microseconds would cause an unexpected time tracking in the logs,
    ///
    /// therefore, in this specific case, both milliseconds and microseconds will be hidden
    pub async fn hide_microsecs(&self) -> &Self {
        self.inner.write().await.config.set_microsecs_config(true);
        self
    }

    /// ## Description
    /// Configures the log timezone to UTC format. Default is Local time
    pub async fn utc_time(&self) -> &Self {
        self.inner.write().await.config.set_utc_config(true);
        self
    }

    /// ## Description
    /// Configures the log level to be hidden. Default is to show it
    pub async fn hide_level(&self) -> &Self {
        self.inner.write().await.config.set_level_config(true);
        self
    }

    /// ## Description
    /// Configures the log file name, line and column to be hidden. Default is to show them
    pub async fn hide_file_name(&self) -> &Self {
        self.inner.write().await.config.set_file_name_config(true);
        self.inner.write().await.config.set_file_line_config(true);
        self.inner.write().await.config.set_file_column_config(false);
        self
    }

    /// ## Description
    /// Configures the log file line and column to be hidden. Default is to show them
    pub async fn hide_file_line(&self) -> &Self {
        self.inner.write().await.config.set_file_line_config(true);
        self
    }

    /// ## Description
    /// Configures the log file column to be shown. Default is to hide it
    pub async fn show_file_column(&self) -> &Self {
        self.inner.write().await.config.set_file_column_config(true);
        self
    }

    //////////////////
    /* Show methods */
    //////////////////
    /// ## Description
    /// Configures the log date to show the years. Default is to show them
    pub async fn show_years(&self) -> &Self {
        self.inner.write().await.config.set_years_config(false);
        self
    }

    /// ## Description
    /// Configures the log date to show the months. Default is to show them
    pub async fn show_months(&self) -> &Self {
        self.inner.write().await.config.set_months_config(false);
        self
    }

    /// ## Description
    /// Configures the log date to show the days. Default is to show them
    pub async fn show_days(&self) -> &Self {
        self.inner.write().await.config.set_days_config(false);
        self
    }

    /// ## Description
    /// Configures the log time to show the hours. Default is to show them
    pub async fn show_hours(&self) -> &Self {
        self.inner.write().await.config.set_hours_config(false);
        self
    }

    /// ## Description
    /// Configures the log time to show the minutes. Default is to show them
    pub async fn show_minutes(&self) -> &Self {
        self.inner.write().await.config.set_minutes_config(false);
        self
    }

    /// ## Description
    /// Configures the log time to show the seconds. Default is to show them
    pub async fn show_seconds(&self) -> &Self {
        self.inner.write().await.config.set_seconds_config(false);
        self
    }

    /// ## Description
    /// Configures the log time to show the milliseconds. Default is to show them
    ///
    /// ### Warning
    /// Hiding the milliseconds and showing the microseconds would cause an unexpected time tracking in the logs,
    ///
    /// therefore, in this specific case, both milliseconds and microseconds will be hidden
    pub async fn show_millisecs(&self) -> &Self {
        self.inner.write().await.config.set_millisecs_config(false);
        self
    }

    /// ## Description
    /// Configures the log time to show the microseconds. Default is to show them
    ///
    /// ### Warning
    /// Hiding the milliseconds and showing the microseconds would cause an unexpected time tracking in the logs,
    ///
    /// therefore, in this specific case, both milliseconds and microseconds will be hidden
    pub async fn show_microsecs(&self) -> &Self {
        self.inner.write().await.config.set_microsecs_config(false);
        self
    }

    /// ## Description
    /// Configures the log timezone to Local format. Default is Local time
    pub async fn local_time(&self) -> &Self {
        self.inner.write().await.config.set_utc_config(false);
        self
    }

    /// ## Description
    /// Configures the log level to be shown. Default is to show it
    pub async fn show_level(&self) -> &Self {
        self.inner.write().await.config.set_level_config(false);
        self
    }

    /// ## Description
    /// Configures the log file name, line and column to be shown. Default is to show them
    pub async fn show_file_name(&self) -> &Self {
        self.inner.write().await.config.set_file_name_config(false);
        self
    }

    /// ## Description
    /// Configures the log file line and column to be shown. Default is to show them
    pub async fn show_file_line(&self) -> &Self {
        self.inner.write().await.config.set_file_line_config(false);
        self
    }

    /// ## Description
    /// Configures the log file column to be shown. Default is to hide it
    pub async fn hide_file_column(&self) -> &Self {
        self.inner.write().await.config.set_file_column_config(false);
        self
    }

    ///////////////////////////
    /* Length configurations */
    ///////////////////////////
    /// ## Description
    /// Configures the log file name, line and column location content's length. Default is 100 characters
    pub async fn location_content_length(&self, length: usize) -> &Self {
        self.inner.write().await.config.set_location_length(length);
        self
    }

    /// ## Description
    /// Configures the log message content's length. Default is 300 characters
    pub async fn log_content_length(&self, length: usize) -> &Self {
        self.inner.write().await.config.set_log_content_length(length);
        self
    }
}