tlogger 0.1.0

A simple logging library with a neat style.
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
use std::{path::PathBuf, sync::OnceLock};

use logger::Logger;
use styling::*;

pub mod logger;
pub mod prelude;
mod styling;
mod tests;

/// Default configurations
pub const COLORS: Colors = Colors {
    info: "\x1b[96m",    // Cyan
    warn: "\x1b[93m",    // Yellow
    error: "\x1b[91m",   // Red
    success: "\x1b[92m", // Green
    debug: "\x1b[95m",   // Magenta
    dim: "\x1b[2m",      // Dimmed
    bold: "\x1b[1m",     // Bold
    reset: "\x1b[0m",    // Reset
};

pub const SYMBOLS: Symbols = Symbols {
    info: "",
    warn: "",
    error: "",
    success: "",
    debug: "",
    separator: "",
    bullet: "",
};

pub const BORDERS: Borders = Borders {
    top_left: "",
    top_right: "",
    bottom_left: "",
    bottom_right: "",
    horizontal: "",
    vertical: "",
};

pub static LOGGER: OnceLock<Logger> = OnceLock::new();
pub static DEBUG: OnceLock<bool> = OnceLock::new();

/// Initializes the logger
///
/// Logs are generated based on the current day.
/// All logs are stored in the directory specified by `path`.
/// With the name format of `YYYY-MM-DD.log`.
pub fn init_logger<P: Into<PathBuf>>(path: P) -> std::io::Result<()> {
    let logger = Logger::new(path)?;
    LOGGER.set(logger).unwrap_or(());
    Ok(())
}

/// Debug is enabled by default
///
/// If set to false all `debug` macros will not be printed to the console, but will
/// still be logged to the log file.
pub fn set_debug(debug: bool) {
    DEBUG.set(debug).unwrap_or(());
}

#[inline]
pub fn get_timestamp() -> String {
    chrono::Local::now().format("%H:%M:%S%.3f").to_string()
}

pub fn create_styled_box(
    color: &str,
    symbol: &str,
    title: &str,
    message: &str,
    width: usize,
) -> String {
    fn wrap_text(text: &str, width: usize) -> String {
        let mut wrapped = String::new();
        let mut line_length = 0;
        let mut first_word = true;

        for word in text.split_whitespace() {
            let word_length = word.len();
            if line_length + word_length + (!first_word as usize) > width - 4 {
                wrapped.push('\n');
                line_length = 0;
                first_word = true;
            }
            if !first_word {
                wrapped.push(' ');
                line_length += 1;
            }
            wrapped.push_str(word);
            line_length += word_length;
            first_word = false;
        }
        wrapped
    }

    let wrapped_message = wrap_text(message, width);
    let message_lines: Vec<&str> = wrapped_message.lines().collect();
    let mut result = String::new();

    // Get timestamp
    let timestamp = chrono::Local::now().format("%H:%M:%S").to_string();
    let timestamp_display = format!("{}", timestamp);

    // Calculate spaces needed between title and timestamp
    let total_space = width - title.len() - timestamp_display.len() - symbol.len() - 1; // Adjusted for symbol and corners

    // Top border with symbol, title and timestamp
    result.push_str(&format!(
        "{}{}{}{} {}{}{}{}{}{}{}{}\n",
        color,
        BORDERS.top_left,
        COLORS.bold,
        symbol,
        title,
        color,
        BORDERS.horizontal.repeat(total_space),
        COLORS.dim,
        timestamp_display,
        COLORS.reset,
        color,
        BORDERS.top_right
    ));

    // Message lines
    for line in message_lines {
        result.push_str(&format!(
            "{}{} {:<width$} {}{}\n",
            color,
            BORDERS.vertical,
            line,
            BORDERS.vertical,
            COLORS.reset,
            width = width - 4
        ));
    }

    // Bottom border
    result.push_str(&format!(
        "{}{}{}{}{}\n",
        color,
        BORDERS.bottom_left,
        BORDERS.horizontal.repeat(width - 2),
        BORDERS.bottom_right,
        COLORS.reset
    ));

    result
}

pub fn create_box(title: &str, message: &str, width: usize) -> String {
    let mut result = String::new();
    let message_lines: Vec<&str> = message.lines().collect();
    let max_width = width.max(message_lines.iter().map(|l| l.len()).max().unwrap_or(0) + 2);

    // Top border with title
    result.push_str(&format!("{}{}", BORDERS.top_left, BORDERS.horizontal));
    result.push_str(title);
    result.push_str(BORDERS.horizontal);
    let remaining_width = max_width - title.len() - 1;
    result.push_str(&format!(
        "{}{}\n",
        BORDERS.horizontal.repeat(remaining_width),
        BORDERS.top_right
    ));

    // Message lines
    for line in message_lines {
        result.push_str(&format!(
            "{} {:<width$} {}\n",
            BORDERS.vertical,
            line,
            BORDERS.vertical,
            width = max_width - 2
        ));
    }

    // Bottom border
    result.push_str(&format!(
        "{}{}{}\n",
        BORDERS.bottom_left,
        BORDERS.horizontal.repeat(max_width),
        BORDERS.bottom_right
    ));

    result
}

#[allow(dead_code)]
pub fn strip_ansi_codes(s: &str) -> String {
    let re = regex::Regex::new(r"\x1b\[[0-9;]*m").unwrap();
    re.replace_all(s, "").to_string()
}

#[macro_export]
macro_rules! info_box {
    ($title:expr, $($arg:tt)*) => {
        print!("{}", $crate::create_styled_box(
            $crate::COLORS.info,
            $crate::SYMBOLS.info,
            $title,
            &format!($($arg)*),
            75
        ));
        let log = make_log!(
            $crate::COLORS.debug,
            $crate::SYMBOLS.debug,
            $title,
            $($arg)*
        );

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&log);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    };
}

#[macro_export]
macro_rules! warn_box {
    ($title:expr, $($arg:tt)*) => {
        print!("{}", $crate::create_styled_box(
            $crate::COLORS.warn,
            $crate::SYMBOLS.warn,
            $title,
            &format!($($arg)*),
            75
        ));
        let log = make_log!(
            $crate::COLORS.debug,
            $crate::SYMBOLS.debug,
            $title,
            $($arg)*
        );

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&log);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    };
}

#[macro_export]
macro_rules! error_box {
    ($title:expr, $($arg:tt)*) => {
        eprint!("{}", $crate::create_styled_box(
            $crate::COLORS.error,
            $crate::SYMBOLS.error,
            $title,
            &format!($($arg)*),
            75
        ));
        let log = make_log!(
            $crate::COLORS.debug,
            $crate::SYMBOLS.debug,
            $title,
            $($arg)*
        );

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&log);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    };
}

#[macro_export]
macro_rules! success_box {
    ($title:expr, $($arg:tt)*) => {
        print!("{}", $crate::create_styled_box(
            $crate::COLORS.success,
            $crate::SYMBOLS.success,
            $title,
            &format!($($arg)*),
            75
        ));
        let log = make_log!(
            $crate::COLORS.debug,
            $crate::SYMBOLS.debug,
            $title,
            $($arg)*
        );

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&log);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    };
}

#[macro_export]
macro_rules! debug_box {
    ($title:expr, $($arg:tt)*) => {
        if *$crate::DEBUG.get().unwrap_or(&true) {
            print!("{}", $crate::create_styled_box(
                $crate::COLORS.debug,
                $crate::SYMBOLS.debug,
                $title,
                &format!($($arg)*),
                75
            ));
        }
        
        let log = make_log!(
            $crate::COLORS.debug,
            $crate::SYMBOLS.debug,
            $title,
            $($arg)*
        );

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&log);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    };
}

#[macro_export]
macro_rules! make_log {
    ($color:expr, $symbol:expr, $title:expr, $($arg:tt)*) => {{
        format!(
            "{}{} {} {}{}{}{} {} {}{}{}{} {}",
            $color,
            $symbol,
            $crate::COLORS.reset,
            $crate::COLORS.dim,
            $crate::get_timestamp(),
            $crate::COLORS.reset,
            $crate::COLORS.dim,
            $crate::SYMBOLS.separator,
            $crate::COLORS.reset,
            $crate::COLORS.bold,
            $title,
            $crate::COLORS.reset,
            format!($($arg)*)
        )
    }};
}

#[macro_export]
macro_rules! info {
    ($title:expr, $($arg:tt)*) => {{
        let msg = make_log!(
            $crate::COLORS.info,
            $crate::SYMBOLS.info,
            $title,
            $($arg)*
        );
        println!("{msg}");

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&msg);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    }};
}

#[macro_export]
macro_rules! warn {
    ($title:expr, $($arg:tt)*) => {{
        let msg = make_log!(
            $crate::COLORS.warn,
            $crate::SYMBOLS.warn,
            $title,
            $($arg)*
        );
        println!("{msg}");

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&msg);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    }};
}

#[macro_export]
macro_rules! error {
    ($title:expr, $($arg:tt)*) => {{
        let msg = make_log!(
            $crate::COLORS.error,
            $crate::SYMBOLS.error,
            $title,
            $($arg)*
        );
        eprintln!("{msg}");

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&msg);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    }};
}

#[macro_export]
macro_rules! success {
    ($title:expr, $($arg:tt)*) => {{
        let msg = make_log!(
            $crate::COLORS.success,
            $crate::SYMBOLS.success,
            $title,
            $($arg)*
        );
        println!("{msg}");

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&msg);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    }};
}

#[macro_export]
macro_rules! debug {
    ($title:expr, $($arg:tt)*) => {{
        let msg = make_log!(
            $crate::COLORS.debug,
            $crate::SYMBOLS.debug,
            $title,
            $($arg)*
        );
        if *$crate::DEBUG.get().unwrap_or(&true) {
            println!("{msg}");
        }

        if let Some(logger) = $crate::LOGGER.get() {
            let clean_log = $crate::strip_ansi_codes(&msg);
            if let Err(e) = logger.log(&clean_log) {
                eprintln!("Error logging to file: {e}");
            }
        }
    }};
}