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
// Copyright © 2022-2023 Mini Functions. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//!
//! # A Rust library that implements application-level logging with a simple, readable output format
//!
//! [![Rust](https://raw.githubusercontent.com/sebastienrousseau/vault/main/assets/mini-functions/logo/logo-rlg.svg)](https://minifunctions.com)
//!
//! <center>
//!
//! [![Rust](https://img.shields.io/badge/rust-f04041?style=for-the-badge&labelColor=c0282d&logo=rust)](https://www.rust-lang.org)
//! [![Crates.io](https://img.shields.io/crates/v/mini-functions.svg?style=for-the-badge&color=success&labelColor=27A006)](https://crates.io/crates/mini-functions)
//! [![Lib.rs](https://img.shields.io/badge/lib.rs-v0.0.8-success.svg?style=for-the-badge&color=8A48FF&labelColor=6F36E4)](https://lib.rs/crates/mini-functions)
//! [![GitHub](https://img.shields.io/badge/github-555555?style=for-the-badge&labelColor=000000&logo=github)](https://github.com/sebastienrousseau/mini-functions)
//! [![License](https://img.shields.io/crates/l/mini-functions.svg?style=for-the-badge&color=007EC6&labelColor=03589B)](http://opensource.org/licenses/MIT)
//!
//! </center>
//!
//! ## Overview
//!
//! RustLogs (RLG) is a library that implements application-level
//! logging in a simple, readable output format. The library provides
//! logging APIs and various helper macros that simplify many common
//! logging tasks.

//!
//! ## Features
//!
//!- Supports many log levels: `ALL`, `DEBUG`, `DISABLED`, `ERROR`,
//!  `FATAL`, `INFO`, `NONE`, `TRACE`, `VERBOSE` and `WARNING`,
//!- Provides structured log formats that are easy to parse and filter,
//!- Compatible with multiple output formats including:
//!  - Common Event Format (CEF),
//!  - Extended Log Format (ELF),
//!  - Graylog Extended Log Format (GELF),
//!  - JavaScript Object Notation (JSON),
//!  - NCSA Common Log Format (CLF),
//!  - W3C Extended Log File Format (W3C),
//!  - and many more
//!
//! ## Usage
//!
//! - [`serde`][]: Enable serialization/deserialization via serde
//!
//! [`serde`]: https://github.com/serde-rs/serde
//!
#![cfg_attr(feature = "bench", feature(test))]
#![deny(dead_code)]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![forbid(unsafe_code)]
#![warn(unreachable_pub)]
#![doc(
    html_favicon_url = "https://raw.githubusercontent.com/sebastienrousseau/vault/main/assets/mini-functions/icons/ico-rlg.svg",
    html_logo_url = "https://raw.githubusercontent.com/sebastienrousseau/vault/main/assets/mini-functions/icons/ico-rlg.svg",
    html_root_url = "https://docs.rs/rlg"
)]
#![crate_name = "rlg"]
#![crate_type = "lib"]

use tokio::io::{self, AsyncWriteExt};
use std::fmt;
use std::fmt::Write as FmtWrite; // Import the write trait for formatting strings
use std::io::{Write, stdout}; // Import the standard library's Write trait for flushing stdout

/// The `macros` module contains functions for generating macros.
pub mod macros;

#[derive(Debug, Clone, PartialEq, PartialOrd)]
/// An enumeration of the different log formats that can be used.
pub enum LogFormat {
    /// The log format is set to CLF.
    CLF,
    /// The log format is set to JSON.
    JSON,
    /// The log format is set to CEF.
    CEF,
    /// The log format is set to ELF.
    ELF,
    /// The log format is set to W3C.
    W3C,
    /// The log format is set to GELF.
    GELF,
}

impl fmt::Display for LogFormat {
    /// Implements [`LogFormat`] to display the log format as a string.
    /// It allows the LogFormat enumeration to be used with the write!
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LogFormat::CEF => write!(f, "CEF"),
            LogFormat::CLF => write!(f, "CLF"),
            LogFormat::ELF => write!(f, "ELF"),
            LogFormat::GELF => write!(f, "GELF"),
            LogFormat::JSON => write!(f, "JSON"),
            LogFormat::W3C => write!(f, "W3C"),
        }
    }
}

/// Implements [`Log`] to log a message to the console with a simple,
/// readable output format.
///
/// # Arguments
///
/// * `session_id` - A string slice that holds a session ID. The session
///    ID is a unique identifier for the current session. A random GUID
///    (Globally Unique Identifier) is generated by default.
/// * `time` - A string slice that holds the timestamp in ISO 8601
///    format.
/// * `level` - A string slice that holds the level (INFO, WARN, ERROR,
///     etc.).
/// * `component` - A string slice that holds the component name.
/// * `description` - A string slice that holds the description of the
///    log message.
///

#[derive(Debug, Clone, PartialEq, PartialOrd)]
/// An enumeration of the different levels that a log message can have.
/// Each variant of the enumeration represents a different level of
/// importance.
///
/// # Arguments
///
/// * `ALL` - The log level is set to all.
/// * `DEBUG` - The log level is set to debug.
/// * `DISABLED` - The log level is set to disabled.
/// * `ERROR` - The log level is set to error.
/// * `FATAL` - The log level is set to fatal.
/// * `INFO` - The log level is set to info.
/// * `NONE` - The log level is set to none.
/// * `TRACE` - The log level is set to trace.
/// * `VERBOSE` - The log level is set to verbose.
/// * `WARNING` - The log level is set to warning.
///
pub enum LogLevel {
    /// The log level is set to all.
    ALL,
    /// The log level is set to debug.
    DEBUG,
    /// The log level is set to disabled.
    DISABLED,
    /// The log level is set to error.
    ERROR,
    /// The log level is set to fatal.
    FATAL,
    /// The log level is set to info.
    INFO,
    /// The log level is set to none.
    NONE,
    /// The log level is set to trace.
    TRACE,
    /// The log level is set to verbose.
    VERBOSE,
    /// The log level is set to warning.
    WARNING,
}

/// Implements [`LogLevel`] to display the log level as a string. It
/// allows the LogLevel enumeration to be used with the write! and
/// print! macros. It provides a human-readable string representation of
/// the variant, that will be used when displaying the log message.
impl fmt::Display for LogLevel {
    /// Implements [`LogLevel`] to display the log level as a string.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LogLevel::ALL => write!(f, "ALL"),
            LogLevel::DEBUG => write!(f, "DEBUG"),
            LogLevel::DISABLED => write!(f, "DISABLED"),
            LogLevel::ERROR => write!(f, "ERROR"),
            LogLevel::FATAL => write!(f, "FATAL"),
            LogLevel::INFO => write!(f, "INFO"),
            LogLevel::NONE => write!(f, "NONE"),
            LogLevel::TRACE => write!(f, "TRACE"),
            LogLevel::VERBOSE => write!(f, "VERBOSE"),
            LogLevel::WARNING => write!(f, "WARNING"),
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, PartialOrd)]
/// The `Log` struct provides an easy way to log a message to the
/// console. It contains a set of defined fields to create a simple,
/// log message with a readable output format.
///
/// # Arguments
///
/// * `session_id` - A string slice that holds a session ID. The session
///    ID is a unique identifier for the current session. A random GUID
///    (Globally Unique Identifier) is generated by default.
/// * `time` - A string slice that holds the timestamp in ISO 8601
///    format.
/// * `level` - A string slice that holds the level (INFO, WARN, ERROR,
///     etc.).
/// * `component` - A string slice that holds the component name.
/// * `description` - A string slice that holds the description of the
///    log message.
///
pub struct Log {
    /// A string that holds a session ID. The session ID is a unique
    /// identifier for the current session. A random GUID (Globally
    /// Unique Identifier) is generated by default.
    pub session_id: String,
    /// A string that holds the timestamp in ISO 8601 format.
    pub time: String,
    /// A string that holds the level (INFO, WARN, ERROR, etc.).
    pub level: LogLevel,
    /// A string that holds the component name.
    pub component: String,
    /// A string that holds the description of the log message.
    pub description: String,
    /// A string that holds the log format.
    pub format: LogFormat,
}

/// This implementation allows the Log struct to be created with default
/// values. It creates a new instance of the Log struct with empty
/// strings for the session_id, time, component and description fields,
///  and LogLevel::INFO for level field. This is useful when creating a
/// new instance of the Log struct. It allows the struct to be created
/// with default values, and then the fields can be set to the desired
/// values.
impl Default for Log {
    /// This implementation allows the Log struct to be created with
    /// default values.
    fn default() -> Log {
        Log {
            session_id: String::default(),
            time: String::default(),
            level: LogLevel::INFO,
            component: String::default(),
            description: String::default(),
            format: LogFormat::CLF,
        }
    }
}

impl Log {
    /// Logs a message asynchronously using a pre-allocated buffer to reduce memory allocation.
    /// The message is formatted according to the specified log format and then written to a file.
    /// Additionally, the message is printed to the standard output and the output buffer is flushed.
    ///
    /// # Errors
    ///
    /// Returns an `io::Result<()>` indicating the outcome of the logging operation.
    /// An error is returned if there's an issue with string formatting or IO operations (file writing or flushing stdout).
    ///
    pub async fn log(&self) -> io::Result<()> {
        let mut log_message = String::with_capacity(256);

        let write_result = match self.format {
            LogFormat::CLF => write!(
                log_message,
                "SessionID={} Timestamp={} Description={} Level={} Component={} Format=CLF",
                self.session_id, self.time, self.level, self.component, self.description
            ),
            LogFormat::JSON => write!(
                log_message,
                "{{\"SessionID\":\"{}\",\"Timestamp\":\"{}\",\"Level\":\"{}\",\"Component\":\"{}\",\"Description\":\"{}\"}} Format=JSON",
                self.session_id, self.time, self.level, self.component, self.description
            ),
            LogFormat::CEF => write!(
                log_message,
                "CEF:0|{}|{}|{}|{}|{}|CEF",
                self.session_id, self.time, self.level, self.component, self.description
            ),
            LogFormat::ELF => write!(
                log_message,
                "ELF:0|{}|{}|{}|{}|{}|ELF",
                self.session_id, self.time, self.level, self.component, self.description
            ),
            LogFormat::W3C => write!(
                log_message,
                "W3C:0|{}|{}|{}|{}|{}|W3C",
                self.session_id, self.time, self.level, self.component, self.description
            ),
            LogFormat::GELF => write!(
                log_message,
                "GELF:0|{}|{}|{}|{}|{}|GELF",
                self.session_id, self.time, self.level, self.component, self.description
            ),
        };

        // Converting std::fmt::Error to std::io::Error
        if let Err(e) = write_result {
            return Err(io::Error::new(io::ErrorKind::Other, e));
        }

        // Writing to a file asynchronously
        let mut file = tokio::fs::File::create("log.txt").await?;
        file.write_all(log_message.as_bytes()).await?;

        // Printing to stdout and flushing
        println!("{log_message}");
        stdout().flush()?;

        Ok(())
    }

    /// Creates a new instance of the `Log` struct with the provided
    /// parameters.
    ///
    /// # Parameters
    /// * `component`: A string slice representing the component.
    /// * `description`: A string slice representing the log description.
    /// * `format`: A string slice representing the log format.
    /// * `level`: A string slice representing the log level.
    /// * `session_id`: A string slice representing the session ID.
    /// * `time`: A string slice representing the timestamp.
    ///
    /// # Returns
    ///
    /// A new instance of the `Log` struct with the provided parameters.
    #[must_use]
    pub fn new(
        session_id: &str,
        time: &str,
        level: &LogLevel,
        component: &str,
        description: &str,
        format: &LogFormat,
    ) -> Self {
        Self {
            session_id: session_id.to_string(),
            time: time.to_string(),
            level: level.clone(),
            component: component.to_string(),
            description: description.to_string(),
            format: format.clone(),
        }
    }
}

impl fmt::Display for Log {
    /// Formats the value using the given formatter.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.format {
            LogFormat::CLF => {
                write!(
                    f,
                    "SessionID={} Timestamp={} Description={} Level={} Component={}",
                    self.session_id, self.time, self.description, self.level, self.component
                )
                .expect("Unable to write log message");
                Ok(())
            }
            LogFormat::JSON => {
                write!(
                f,
                "{{\"SessionID\":\"{}\",\"Timestamp\":\"{}\",\"Level\":\"{}\",\"Component\":\"{}\",\"Description\":\"{}\",\"Format\":\"JSON\"}}",
                self.session_id, self.time, self.level, self.component, self.description)
                .expect("Unable to write log message");
                Ok(())
            }
            LogFormat::CEF => {
                write!(
                    f,
                    "CEF:0|{}|{}|{}|{}|{}|CEF",
                    self.session_id, self.time, self.level, self.component, self.description
                )
                .expect("Unable to write log message");
                Ok(())
            }
            LogFormat::ELF => {
                write!(
                    f,
                    "ELF:0|{}|{}|{}|{}|{}|ELF",
                    self.session_id, self.time, self.level, self.component, self.description
                )
                .expect("Unable to write log message");
                Ok(())
            }
            LogFormat::W3C => {
                write!(
                    f,
                    "W3C:0|{}|{}|{}|{}|{}|W3C",
                    self.session_id, self.time, self.level, self.component, self.description
                )
                // self.session_id, self.time, self.level, self.component, self.description)
                .expect("Unable to write log message");
                Ok(())
            }
            LogFormat::GELF => {
                write!(
                    f,
                    r#"{{
                            "version": "1.1",
                            "host": "{}",
                            "short_message": "{}",
                            "level": "{:?}",
                            "timestamp": "{}",
                            "_component": "{}",
                            "_session_id": "{}"
                        }}"#,
                    self.component,
                    self.description,
                    self.level,
                    self.time,
                    self.component,
                    self.session_id
                )
                .expect("Unable to write log message");
                Ok(())
            }
        }
    }
}