loggit 0.1.9

Loggit is a lightweight, easy-to-use logging library 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
#![allow(unused_imports)] // temp for dev
use std::{
    fs::{self, File},
    io::Write,
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

use crate::{
    logger::{
        init, load_config_from_file,
        set_errors::{
            AddRotationError, ReadFromConfigFileError, SetArchiveDirError, SetColorizedError,
            SetCompressionError, SetFileError, SetLevelFormattingError, SetLogLevelError,
            SetPrintToTerminalError,
        },
    },
    Level, CONFIG,
};
// Assuming Config is accessible as crate::Config because this file is in src/tests/
use crate::logger::formatter::LogFormatter;
use crate::Config as LoggerConfig;

// Helper to create a temporary JSON file
fn temp_json_file(contents: &str) -> PathBuf {
    let mut path = std::env::temp_dir();
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let file_name = format!("loggit_json_test_{}.json", ts);
    path.push(file_name);

    let mut file = File::create(&path)
        .unwrap_or_else(|e| panic!("Failed to create temp json-file at {:?}: {}", path, e));
    write!(file, "{}", contents)
        .unwrap_or_else(|e| panic!("Failed to write temp json-file at {:?}: {}", path, e));
    path
}

// Helper to get a snapshot of the config
fn config_snapshot() -> LoggerConfig {
    CONFIG.read().expect("CONFIG should be readable").clone()
}

// Teardown for archive directories
fn cleanup_archive_dir(path_str: &str) {
    let path = Path::new(path_str);
    if path.exists() && path.is_dir() {
        fs::remove_dir_all(path).ok();
    }
}

#[test]
fn json_enabled_variants() {
    // enabled=false → DisabledToBeUsed
    init();
    let p = temp_json_file(r#"{"enabled": "false"}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::DisabledToBeUsed)
    ));
    fs::remove_file(p).ok();

    // enabled missing (not set) should simply work (Ok)
    init();
    let p = temp_json_file(r#"{"level": "info"}"#); // Other valid field
    assert!(load_config_from_file(p.to_str().unwrap()).is_ok());
    fs::remove_file(p).ok();

    // enabled = true
    init();
    let p = temp_json_file(r#"{"enabled": "true"}"#);
    assert!(load_config_from_file(p.to_str().unwrap()).is_ok());
    fs::remove_file(p).ok();

    // enabled=invalid → ParseError("incorrect value given")
    init();
    let p = temp_json_file(r#"{"enabled": "maybe"}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(
        matches!(&res, Err(ReadFromConfigFileError::ParseError(s)) if s == "incorrect value given"),
        "Unexpected error: {:?}",
        res
    );
    fs::remove_file(p).ok();
}

#[test]
fn json_all_levels_valid() {
    let cases = [
        ("trace", Level::TRACE),
        ("debug", Level::DEBUG),
        ("info", Level::INFO),
        ("warn", Level::WARN),
        ("error", Level::ERROR),
        ("TRACE", Level::TRACE), // Test uppercase
    ];

    for (lvl_str, lvl_enum) in cases {
        init();
        let content = format!(r#"{{"level": "{}"}}"#, lvl_str);
        let p = temp_json_file(&content);
        assert!(load_config_from_file(p.to_str().unwrap()).is_ok());
        let cfg = config_snapshot();
        assert_eq!(cfg.level, lvl_enum, "level `{}` not applied", lvl_str);
        fs::remove_file(p).ok();
    }

    // invalid level value
    init();
    let p = temp_json_file(r#"{"level": "verbose"}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(
        matches!(&res, Err(ReadFromConfigFileError::ParseError(s)) if s == "incorrect value given"),
        "Unexpected error: {:?}",
        res
    );
    fs::remove_file(p).ok();
}

#[test]
fn json_print_to_terminal_variants() {
    init(); // true
    let p_true = temp_json_file(r#"{"print_to_terminal": "true"}"#);
    assert!(load_config_from_file(p_true.to_str().unwrap()).is_ok());
    assert!(config_snapshot().print_to_terminal);
    fs::remove_file(p_true).ok();

    init(); // false
    let p_false = temp_json_file(r#"{"print_to_terminal": "false"}"#);
    assert!(load_config_from_file(p_false.to_str().unwrap()).is_ok());
    assert!(!config_snapshot().print_to_terminal);
    fs::remove_file(p_false).ok();

    init(); // invalid
    let p_invalid = temp_json_file(r#"{"print_to_terminal": "nope"}"#);
    let res = load_config_from_file(p_invalid.to_str().unwrap());
    assert!(
        matches!(&res, Err(ReadFromConfigFileError::ParseError(s)) if s == "incorrect value given"),
        "Unexpected error: {:?}",
        res
    );
    fs::remove_file(p_invalid).ok();
}

#[test]
fn json_colorized_variants() {
    init(); // true
    let p_true = temp_json_file(r#"{"colorized": "true"}"#);
    assert!(load_config_from_file(p_true.to_str().unwrap()).is_ok());
    assert!(config_snapshot().colorized);
    fs::remove_file(p_true).ok();

    init(); // false
    let p_false = temp_json_file(r#"{"colorized": "false"}"#);
    assert!(load_config_from_file(p_false.to_str().unwrap()).is_ok());
    assert!(!config_snapshot().colorized);
    fs::remove_file(p_false).ok();

    init(); // invalid
    let p_invalid = temp_json_file(r#"{"colorized": "rainbow"}"#);
    let res = load_config_from_file(p_invalid.to_str().unwrap());
    assert!(
        matches!(&res, Err(ReadFromConfigFileError::ParseError(s)) if s == "incorrect value given"),
        "Unexpected error: {:?}",
        res
    );
    fs::remove_file(p_invalid).ok();
}

#[test]
fn json_global_formatting_ok_and_bad() {
    init(); // Valid
    let fmt_txt = "[{level}] {message}";
    let p_ok = temp_json_file(&format!(r#"{{"global_formatting": "{}"}}"#, fmt_txt));
    assert!(load_config_from_file(p_ok.to_str().unwrap()).is_ok());

    let cfg = config_snapshot();
    let expected = LogFormatter::parse_from_string(fmt_txt).unwrap();
    assert_eq!(cfg.trace_log_format.parts, expected.parts);
    assert_eq!(cfg.debug_log_format.parts, expected.parts);
    assert_eq!(cfg.info_log_format.parts, expected.parts);
    assert_eq!(cfg.warn_log_format.parts, expected.parts);
    assert_eq!(cfg.error_log_format.parts, expected.parts);
    fs::remove_file(p_ok).ok();

    init(); // Invalid
    let bad_fmt = "<red>[{level}]"; // missing closing <red>
    let p_bad = temp_json_file(&format!(r#"{{"global_formatting": "{}"}}"#, bad_fmt));
    let res = load_config_from_file(p_bad.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::SetLevelFormatting(
            SetLevelFormattingError::IncorrectFormatGiven(_)
        ))
    ));
    fs::remove_file(p_bad).ok();
}

#[test]
fn json_individual_level_formatting() {
    init();
    let trace_fmt_txt = "TRACE: {message}";
    let error_fmt_txt = "ERROR: {file}:{line} {message}";
    let content = format!(
        r#"{{
        "trace_formatting": "{}",
        "error_formatting": "{}"
    }}"#,
        trace_fmt_txt, error_fmt_txt
    );
    let p = temp_json_file(&content);
    assert!(load_config_from_file(p.to_str().unwrap()).is_ok());

    let cfg = config_snapshot();
    let default_fmt = LogFormatter::default(); // Other levels should remain default
    assert_eq!(
        cfg.trace_log_format.parts,
        LogFormatter::parse_from_string(trace_fmt_txt)
            .unwrap()
            .parts
    );
    assert_eq!(cfg.debug_log_format.parts, default_fmt.parts); // Assuming default is not changed
    assert_eq!(
        cfg.error_log_format.parts,
        LogFormatter::parse_from_string(error_fmt_txt)
            .unwrap()
            .parts
    );
    fs::remove_file(p).ok();

    // Test invalid individual format
    init();
    let p_bad = temp_json_file(r#"{"info_formatting": "<blue>{message}"}"#); // missing closing </blue>
    let res = load_config_from_file(p_bad.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::SetLevelFormatting(
            SetLevelFormattingError::IncorrectFormatGiven(_)
        ))
    ));
    fs::remove_file(p_bad).ok();
}

#[test]
fn json_full_file_config_valid() {
    init();
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let archive_dir_name = format!("test_json_archives_full_{}", ts);

    let content = format!(
        r#"{{
        "file_name": "app_{{date}}_{{time}}.log",
        "compression": "zip",
        "rotations": ["1 day", "10 MB", "12:30"],
        "archive_dir": "{}"
    }}"#,
        archive_dir_name
    );
    let p = temp_json_file(&content);
    let load_res = load_config_from_file(p.to_str().unwrap());
    assert!(
        load_res.is_ok(),
        "load_config_from_file failed: {:?}",
        load_res.err()
    );

    let cfg = config_snapshot();
    assert!(
        cfg.file_manager.is_some(),
        "File manager should be configured"
    );
    assert_eq!(cfg.archive_dir, Some(PathBuf::from(&archive_dir_name)));
    assert!(
        Path::new(&archive_dir_name).is_dir(),
        "Archive directory was not created"
    );

    // Check rotations and compression via debug output of file_manager
    let fm_lock = cfg.file_manager.as_ref().unwrap().lock().unwrap();
    let fm_dbg = format!("{:?}", fm_lock);
    println!("{:?}", fm_dbg);
    assert!(fm_dbg.contains("Zip"));
    assert!(fm_dbg.contains("Period")); // "1 day"
    assert!(fm_dbg.contains("Size")); // "10 MB"
    assert!(fm_dbg.contains("Time")); // "12:30"

    cleanup_archive_dir(&archive_dir_name);
    fs::remove_file(p).ok();
}

#[test]
fn json_file_name_invalid_format() {
    init();
    // Forbidden character '<'
    let p = temp_json_file(r#"{"file_name": "test<bad>.log"}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::SetFile(
            SetFileError::UnableToLoadFromString(_)
        ))
    ));
    fs::remove_file(p).ok();
}

#[test]
fn json_compression_without_file_name() {
    init();
    let p = temp_json_file(r#"{"compression": "zip"}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::SetCompression(
            SetCompressionError::FileIsntSet
        ))
    ));
    fs::remove_file(p).ok();
}

#[test]
fn json_invalid_compression_value() {
    init();
    let p = temp_json_file(r#"{"file_name": "app.log", "compression": "rar"}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::SetCompression(
            SetCompressionError::IncorrectCompressionValue
        ))
    ));
    fs::remove_file(p).ok();
}

#[test]
fn json_rotations_without_file_name() {
    init();
    let p = temp_json_file(r#"{"rotations": ["1 day"]}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::AddRotation(
            AddRotationError::FileIsntSet
        ))
    ));
    fs::remove_file(p).ok();
}

#[test]
fn json_invalid_rotation_value() {
    init();
    let p = temp_json_file(r#"{"file_name": "app.log", "rotations": ["invalid rotation"]}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::AddRotation(
            AddRotationError::IncorrectFormatGiven
        ))
    ));
    fs::remove_file(p).ok();
}

#[test]
fn json_empty_rotations_array() {
    init();
    let p = temp_json_file(r#"{"file_name": "app.log", "rotations": []}"#);
    let load_res = load_config_from_file(p.to_str().unwrap());
    assert!(
        load_res.is_ok(),
        "load_config_from_file failed for empty rotations: {:?}",
        load_res.err()
    );

    let cfg = config_snapshot();
    let fm_lock = cfg.file_manager.as_ref().unwrap().lock().unwrap();
    let fm_dbg = format!("{:?}", fm_lock);
    // Check that rotation list is empty in debug string
    assert!(fm_dbg.contains("rotation: []"));
    fs::remove_file(p).ok();
}

#[test]
fn json_archive_dir_creates_directory() {
    init();
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let archive_dir_name = format!("test_json_archive_dir_creation_{}", ts);

    let content = format!(r#"{{"archive_dir": "{}"}}"#, archive_dir_name);
    let p = temp_json_file(&content);
    let result = load_config_from_file(p.to_str().unwrap());
    assert!(
        result.is_ok(),
        "load_config_from_file failed: {:?}",
        result.err()
    );

    let cfg = config_snapshot();
    assert_eq!(cfg.archive_dir, Some(PathBuf::from(&archive_dir_name)));
    assert!(
        Path::new(&archive_dir_name).is_dir(),
        "Archive directory was not created"
    );

    cleanup_archive_dir(&archive_dir_name);
    fs::remove_file(p).ok();
}

#[test]
fn json_archive_dir_path_is_file() {
    init();
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let file_acting_as_dir_name = format!("test_json_file_as_dir_{}", ts);

    File::create(&file_acting_as_dir_name)
        .unwrap()
        .write_all(b"i am a file")
        .unwrap();

    let content = format!(r#"{{"archive_dir": "{}"}}"#, file_acting_as_dir_name);
    let p = temp_json_file(&content);
    let result = load_config_from_file(p.to_str().unwrap());

    assert!(matches!(
        result,
        Err(ReadFromConfigFileError::SetArchiveDirError(
            SetArchiveDirError::UnableToCreateDir(_)
        ))
    ));

    fs::remove_file(file_acting_as_dir_name).ok();
    fs::remove_file(p).ok();
}

#[test]
fn json_empty_file() {
    init();
    let p = temp_json_file(""); // Empty content
    let res = load_config_from_file(p.to_str().unwrap());
    // serde_json::from_str on empty string gives "EOF while parsing a value"
    assert!(matches!(&res, Err(ReadFromConfigFileError::ParseError(s)) if s.contains("EOF")));
    fs::remove_file(p).ok();
}

#[test]
fn json_malformed_file() {
    init();
    let p = temp_json_file(r#"{"level": "info",malformed}"#); // Malformed JSON
    let res = load_config_from_file(p.to_str().unwrap());
    assert!(matches!(&res, Err(ReadFromConfigFileError::ParseError(_))));
    fs::remove_file(p).ok();
}

#[test]
fn json_unknown_fields_ignored() {
    init();
    let p = temp_json_file(r#"{"level": "warn", "unknown_field": "some_value"}"#);
    let load_res = load_config_from_file(p.to_str().unwrap());
    assert!(
        load_res.is_ok(),
        "load_config_from_file failed: {:?}",
        load_res.err()
    );
    // Check that known field was applied
    assert_eq!(config_snapshot().level, Level::WARN);
    fs::remove_file(p).ok();
}

#[test]
fn json_incorrect_value_types() {
    init();
    // level expects a string like "info", not a number
    let p = temp_json_file(r#"{"level": 123}"#);
    let res = load_config_from_file(p.to_str().unwrap());
    // serde_json will fail to deserialize: invalid type: integer `123`, expected a string
    assert!(
        matches!(&res, Err(ReadFromConfigFileError::ParseError(s)) if s.contains("invalid type"))
    );
    fs::remove_file(p).ok();

    init();
    // rotations expects an array of strings, not a single string
    let p_rot_str = temp_json_file(r#"{"rotations": "1 day"}"#);
    let res_rot_str = load_config_from_file(p_rot_str.to_str().unwrap());
    assert!(
        matches!(&res_rot_str, Err(ReadFromConfigFileError::ParseError(s)) if s.contains("invalid type"))
    );
    fs::remove_file(p_rot_str).ok();
}

#[test]
fn json_missing_file() {
    init();
    let bogus_path = "/no/such/path/to_json_file.json";
    let res = load_config_from_file(bogus_path);
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::ReadFileError(_))
    ));
}

#[test]
fn json_incorrect_extension_but_valid_json_content() {
    init();
    // File has .txt extension but JSON content, load_config_from_file should dispatch by extension
    let mut path = std::env::temp_dir();
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    path.push(format!("loggit_json_test_wrong_ext_{}.txt", ts)); // Wrong extension
    let mut file = File::create(&path).unwrap();
    write!(file, r#"{{"level": "error"}}"#).unwrap(); // Valid JSON content

    let res = load_config_from_file(path.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::IncorrectFileExtension)
    ));
    fs::remove_file(path).ok();
}

#[test]
fn json_file_name_without_extension_in_path() {
    init();
    let mut path = std::env::temp_dir();
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    path.push(format!("loggit_json_test_no_ext_{}", ts)); // No extension in path

    // We don't need to create the file, as the error should occur before reading.
    // `path.to_str().unwrap()` is the argument to `load_config_from_file`.
    // `load_config_from_file` calls `parse_config_file` which checks `path.contains(".")`

    let res = load_config_from_file(path.to_str().unwrap());
    assert!(matches!(
        res,
        Err(ReadFromConfigFileError::IncorrectFileName)
    ));
    // No file to remove as it wasn't necessarily created by helper if path itself is bad
}