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
//! Provides interfaces for logging
//!
//! This includes functionality to log messages of various levels (Debug, Info, Warning, ...) to different backends,
//! as well as setting the desired log level

use chrono::Utc;
use colored::Colorize;
use env_logger::Env;
use log::{Level, Record};
use std::io::Write;
use std::path::Path;

/// SDK Log Level Enum
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    strum_macros::Display,
    strum_macros::EnumString,
    strum_macros::FromRepr,
)]
pub enum SDKLogLevel {
    /// A critical error.
    /// Maps to "Error" in log crate.
    Critical = 1,
    /// A standard error.
    /// Maps to "Error" in log crate.
    Error,
    /// A warning.
    /// Maps to "Warning in log crate.
    Warning,
    /// An informative message.
    /// Logs to "Info" in log crate.
    #[default]
    Info,
    /// A Debug message.
    /// Maps to "Debug" in log crate.
    Debug,
    /// A trace message
    /// Maps to "Trace" in log crate
    Trace,
}
// The logging environment variable used to overwrite the logging levels.
static LOG_ENV_VAR: &str = "CELP_LOG";

/// SDKLogLevel implementation
impl SDKLogLevel {
    /// Returns max logging level available.
    ///
    /// # Example
    /// ```rust,no_run
    /// use celp_sdk::logger::log::SDKLogLevel;
    ///
    /// let max_level = SDKLogLevel::max();
    /// ```
    pub fn max() -> SDKLogLevel {
        SDKLogLevel::Debug
    }

    /// Returns min logging level available.
    ///
    /// # Example
    /// ```rust,no_run
    /// use celp_sdk::logger::log::SDKLogLevel;
    ///
    /// let min_level = SDKLogLevel::min();
    /// ```
    pub fn min() -> SDKLogLevel {
        SDKLogLevel::Critical
    }
}

/// Implement 'From' and 'Into' functionality to convert the Log levels we like to the levels that the crate uses.
/// This means we can do something like: 'let log_level: Level = SDKLogLevel::Info.into();'
impl From<SDKLogLevel> for Level {
    /// Converts an SDKLogLevel value to a Level value
    ///
    /// # Example
    /// ```rust,no_run
    /// use log::Level;
    /// use celp_sdk::logger::log::SDKLogLevel;
    ///
    /// let converted_log_level: Level = SDKLogLevel::default().into();
    /// ```
    fn from(sdk_ll: SDKLogLevel) -> Self {
        match sdk_ll {
            SDKLogLevel::Critical => Level::Error,
            SDKLogLevel::Error => Level::Error,
            SDKLogLevel::Warning => Level::Warn,
            SDKLogLevel::Info => Level::Info,
            SDKLogLevel::Debug => Level::Debug,
            SDKLogLevel::Trace => Level::Trace,
        }
    }
}

/// Same as above, but the other way around.
impl From<Level> for SDKLogLevel {
    /// Converts a Level value to an SDKLogLevel value
    ///
    /// # Example
    /// ```rust,no_run
    /// use log::Level;
    /// use celp_sdk::logger::log::SDKLogLevel;
    ///
    /// let converted_log_level: SDKLogLevel = Level::Error.into();
    /// ```
    fn from(sdk_ll: Level) -> Self {
        match sdk_ll {
            Level::Error => SDKLogLevel::Error,
            Level::Warn => SDKLogLevel::Warning,
            Level::Info => SDKLogLevel::Info,
            Level::Debug => SDKLogLevel::Debug,
            Level::Trace => SDKLogLevel::Trace,
        }
    }
}

/// Initialise the logging functionality to a certain level.
///
/// # Arguments
///
/// * `module_name` - A string to denote the calling application. It can be any string. It does not have to match the exact application name.
/// * `log_level` - The level of logging to use. If not given, will use default logging level.
///
/// # Example
/// ```rust,no_run
/// use celp_sdk::logger::log::{SDKLogLevel, init_logger};
///
/// let app_name = "test";
/// let level = SDKLogLevel::default();
///
/// init_logger(app_name, Some(level));
/// ```
pub fn init_logger(module_name: &str, log_level: Option<SDKLogLevel>) {
    // Set default logging level (converts to "Info" for our logging levels).
    let mut converted_log_level: Level = SDKLogLevel::default().into();
    // Convert the SDKLogLevel to standard Level type
    // If a log level was specified.
    if let Some(ll) = log_level {
        // Convert the SDKLogLevel to Level.
        converted_log_level = ll.into();
    }

    // Set up a new Builder instance here so that we can ignore some of the presets like the "RUST_LOG" environment variable and such.
    let mut builder = env_logger::Builder::new();

    // Convert the 'Level' type to 'LevelFilter' type with 'to_level_filter'.
    // NOTE: After some testing, it is seen that `filter_level` is required first before setting `filter_module` or else the level filter does not get set correctly.
    builder.filter_level(converted_log_level.to_level_filter());
    // Then set the filter for the module.
    builder.filter_module(module_name, converted_log_level.to_level_filter());

    // Need to check if the custom environment variable is set first.
    if std::env::var(LOG_ENV_VAR).is_ok() {
        // Specify a custom environment variable other than the default "RUST_LOG"
        let env = Env::new().filter(LOG_ENV_VAR);
        // Set the environment variable to use for overwriting log levels.
        builder.parse_env(env);
    }
    // Set the output as stdout (env_logger uses stderr by default).
    builder.target(env_logger::Target::Stdout);

    //Format the output message.
    builder.format(|buf, record| writeln!(buf, "{}", format_log_str(record)));

    // Initialise the builder.
    builder.init();
}

/// Format the log string in a similar manner to C++ SDK logger.
/// Will output in the following format:
/// "[1970-01-01T12:34:56.012345Z] [main.rs:123] [---D---] log message"
fn format_log_str(record: &Record) -> String {
    // Get the current time.
    let now = Utc::now();
    let formatted_time = now.format("[%Y-%m-%dT%H:%M:%S%.6fZ]").to_string();
    // Get the file name or use the default string.
    let filename = record.file().unwrap_or("Unknown file path");
    // Convert to Path object to get the file name at end of string.
    let path = Path::new(filename);
    let line = record.line().unwrap_or(0);
    // Convert the log level to a str, iterator over the characters and grab the first letter.
    let sdk_log_level: SDKLogLevel = record.level().into();
    let short_log_level_char = sdk_log_level.to_string().chars().next().unwrap();
    let mut short_log_level_str = String::from("---X---");
    // Replace the "X" with the correct character.
    short_log_level_str.replace_range(3..4, &short_log_level_char.to_string());
    // Based on the log level, the string should be a different colour.
    // TODO: Confirm color choice with C++ version.
    let short_log_level_str_colored = match sdk_log_level {
        SDKLogLevel::Critical => short_log_level_str.purple(),
        SDKLogLevel::Error => short_log_level_str.red(),
        SDKLogLevel::Warning => short_log_level_str.yellow(),
        SDKLogLevel::Info => short_log_level_str.green(),
        SDKLogLevel::Debug => short_log_level_str.blue(),
        SDKLogLevel::Trace => short_log_level_str.white(),
    };

    // NOTE: Will not implement thread ID printing for now. Rust doesn't have any nice ways for this library to get the thread ID of the calling application.
    //       We would have to pss the thread ID directly from the calling application. That would just be messy.
    format!(
        "{} [{:?}:{:?}] [{}] {:?}",
        formatted_time,
        path.file_name()
            .unwrap_or(std::ffi::OsStr::new("<unknown>")),
        line,
        short_log_level_str_colored,
        record.args()
    )
}

/// The following macros convert the 'log' crates macros to use our own log levels.
///
/// | SDK      | log   |
/// |__________|_______|
/// | critical | error |
/// | error    | error |
/// | warning  | warn  |
/// | info     | info  |
/// | debug    | debug |
/// | trace    | trace |
///
/// # Example
/// ```rust,no_run
/// use celp_sdk::critical;
///
/// critical!("It all went terribly wrong!");
/// ```
///
pub use log::{debug as _debug, error as _error, info as _info, trace as _trace, warn as _warn};

#[macro_export]
macro_rules! critical {
    ($($arg:tt)*) => {
        // Delegate to the 'log' crates 'error!' macro
        $crate::logger::log::_error!($($arg)*)
    }
}

/// # Example
/// ```rust,no_run
/// use celp_sdk::error;
///
/// error!("Oh oh: {}", "details");
/// ```
#[macro_export]
macro_rules! error {
    ($($arg:tt)*) => {
        // Delegate to the 'log' crates 'error!' macro
        $crate::logger::log::_error!($($arg)*)
    }
}

/// # Example
/// ```rust,no_run
/// use celp_sdk::warning;
///
/// warning!("woopsie: {}", "details");
/// ```
#[macro_export]
macro_rules! warning {
    ($($arg:tt)*) => {
        // Delegate to the 'log' crates 'warning!' macro
        $crate::logger::log::_warn!($($arg)*)
    }
}

/// # Example
/// ```rust,no_run
/// use celp_sdk::info;
///
/// info!("I'd like to tell you about: {}", "what I'm doing now");
/// ```
#[macro_export]
macro_rules! info {
    ($($arg:tt)*) => {
        // Delegate to the 'log' crates 'info!' macro
        $crate::logger::log::_info!($($arg)*)
    }
}

/// # Example
/// ```rust,no_run
/// use celp_sdk::debug;
///
/// debug!("I know you're probably not really interested in this: {}!", "but here it is anyway");
/// ```
#[macro_export]
macro_rules! debug {
    ($($arg:tt)*) => {
        // Delegate to the 'log' crates 'debug!' macro
        $crate::logger::log::_debug!($($arg)*)
    }
}

/// # Example
/// ```rust,no_run
/// use celp_sdk::trace;
///
/// trace!("I'll inundate you with information!");
/// ```
#[macro_export]
macro_rules! trace {
    ($($arg:tt)*) => {
        // Delegate to the 'log' crates 'debug!' macro
        $crate::logger::log::_trace!($($arg)*)
    }
}