firo_logger 1.1.2

A high-performance, feature-rich logger for Rust applications with colored output, structured logging, and advanced configuration
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Formatters for different log output formats.

use crate::config::{Colors, LogLevel, OutputFormat};
use chrono::{DateTime, Local};
use serde_json::json;
use std::collections::HashMap;
use std::fmt::Arguments;

/// Information about the caller of a log statement.
#[derive(Debug, Clone)]
pub struct CallerInfo {
    /// File path where the log was called
    pub file: &'static str,
    /// Line number where the log was called
    pub line: u32,
    /// Module path where the log was called
    pub module: Option<&'static str>,
}

/// Information about the current thread.
#[derive(Debug, Clone)]
pub struct ThreadInfo {
    /// Thread ID
    pub id: String,
    /// Thread name (if available)
    pub name: Option<String>,
}

/// A complete log record with all metadata.
#[derive(Debug, Clone)]
pub struct LogRecord {
    /// Log level
    pub level: LogLevel,
    /// Log message
    pub message: String,
    /// Timestamp when the log was created
    pub timestamp: DateTime<Local>,
    /// Module where the log originated
    pub module: Option<String>,
    /// Caller information
    pub caller: Option<CallerInfo>,
    /// Thread information
    pub thread: Option<ThreadInfo>,
    /// Custom metadata
    pub metadata: HashMap<String, String>,
}

impl LogRecord {
    /// Creates a new log record.
    pub fn new(level: LogLevel, args: Arguments) -> Self {
        Self {
            level,
            message: format!("{args}"),
            timestamp: Local::now(),
            module: None,
            caller: None,
            thread: None,
            metadata: HashMap::new(),
        }
    }

    /// Sets the module information.
    pub fn with_module<S: Into<String>>(mut self, module: S) -> Self {
        self.module = Some(module.into());
        self
    }

    /// Sets the caller information.
    pub fn with_caller(mut self, caller: CallerInfo) -> Self {
        self.caller = Some(caller);
        self
    }

    /// Sets the thread information.
    pub fn with_thread(mut self, thread: ThreadInfo) -> Self {
        self.thread = Some(thread);
        self
    }

    /// Adds custom metadata.
    pub fn with_metadata<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Adds multiple metadata entries.
    pub fn with_metadata_map(mut self, metadata: HashMap<String, String>) -> Self {
        self.metadata.extend(metadata);
        self
    }
}

/// Helper function to center text within a given width.
fn center_text(text: &str, width: usize) -> String {
    let text_len = text.len();
    if text_len >= width {
        return text.to_string();
    }

    let padding = width - text_len;
    let left_padding = padding / 2;
    let right_padding = padding - left_padding;

    format!(
        "{}{}{}",
        " ".repeat(left_padding),
        text,
        " ".repeat(right_padding)
    )
}

/// Trait for formatting log records.
pub trait Formatter: Send + Sync {
    /// Formats a log record into a string.
    fn format(&self, record: &LogRecord) -> String;

    /// Returns whether this formatter supports colors.
    fn supports_colors(&self) -> bool {
        false
    }
}

/// Text formatter with optional colors.
#[derive(Debug, Clone)]
pub struct TextFormatter {
    /// Whether to include colors in output
    pub colors: bool,
    /// DateTime format string
    pub datetime_format: String,
    /// Whether to include caller information
    pub include_caller: bool,
    /// Whether to include thread information
    pub include_thread: bool,
    /// Whether to include module information
    pub include_module: bool,
}

impl Default for TextFormatter {
    fn default() -> Self {
        Self {
            colors: true,
            datetime_format: "%Y-%m-%d %H:%M:%S".to_string(),
            include_caller: false,
            include_thread: false,
            include_module: false,
        }
    }
}

impl TextFormatter {
    /// Creates a new text formatter.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets whether to use colors.
    pub fn with_colors(mut self, colors: bool) -> Self {
        self.colors = colors;
        self
    }

    /// Sets the datetime format.
    pub fn with_datetime_format<S: Into<String>>(mut self, format: S) -> Self {
        self.datetime_format = format.into();
        self
    }

    /// Sets whether to include caller information.
    pub fn with_caller(mut self, include: bool) -> Self {
        self.include_caller = include;
        self
    }

    /// Sets whether to include thread information.
    pub fn with_thread(mut self, include: bool) -> Self {
        self.include_thread = include;
        self
    }

    /// Sets whether to include module information.
    pub fn with_module(mut self, include: bool) -> Self {
        self.include_module = include;
        self
    }
}

impl Formatter for TextFormatter {
    fn format(&self, record: &LogRecord) -> String {
        let timestamp = record.timestamp.format(&self.datetime_format);

        let level_str = if self.colors {
            let color = Colors::for_level(record.level);
            let centered = center_text(record.level.as_str(), 7);
            format!("{}{}{}", color, centered, Colors::RESET)
        } else {
            center_text(record.level.as_str(), 7)
        };

        let mut parts = vec![format!("{}", timestamp), format!("[{}]:", level_str)];

        // Add thread information if requested
        if self.include_thread {
            if let Some(ref thread) = record.thread {
                let thread_info = if let Some(ref name) = thread.name {
                    format!("[{}:{}]", name, thread.id)
                } else {
                    format!("[{}]", thread.id)
                };
                parts.push(thread_info);
            }
        }

        // Add module information if requested
        if self.include_module {
            if let Some(ref module) = record.module {
                parts.push(format!("[{module}]"));
            }
        }

        // Add caller information if requested
        if self.include_caller {
            if let Some(ref caller) = record.caller {
                let caller_info = format!("{}:{}", caller.file, caller.line);
                parts.push(format!("[{caller_info}]"));
            }
        }

        // Add the message
        parts.push(record.message.clone());

        // Add metadata if any
        if !record.metadata.is_empty() {
            let metadata_parts: Vec<String> = record
                .metadata
                .iter()
                .map(|(k, v)| format!("{k}={v}"))
                .collect();
            parts.push(format!("[{}]", metadata_parts.join(", ")));
        }

        parts.join(" ")
    }

    fn supports_colors(&self) -> bool {
        self.colors
    }
}

/// JSON formatter for structured logging.
#[derive(Debug, Clone)]
pub struct JsonFormatter {
    /// Whether to pretty-print JSON
    pub pretty: bool,
    /// DateTime format string
    pub datetime_format: String,
    /// Whether to include caller information
    pub include_caller: bool,
    /// Whether to include thread information
    pub include_thread: bool,
    /// Whether to include module information
    pub include_module: bool,
}

impl Default for JsonFormatter {
    fn default() -> Self {
        Self {
            pretty: false,
            datetime_format: "%Y-%m-%dT%H:%M:%S%.3fZ".to_string(),
            include_caller: true,
            include_thread: true,
            include_module: true,
        }
    }
}

impl JsonFormatter {
    /// Creates a new JSON formatter.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets whether to pretty-print JSON.
    pub fn with_pretty(mut self, pretty: bool) -> Self {
        self.pretty = pretty;
        self
    }

    /// Sets the datetime format.
    pub fn with_datetime_format<S: Into<String>>(mut self, format: S) -> Self {
        self.datetime_format = format.into();
        self
    }

    /// Sets whether to include caller information.
    pub fn with_caller(mut self, include: bool) -> Self {
        self.include_caller = include;
        self
    }

    /// Sets whether to include thread information.
    pub fn with_thread(mut self, include: bool) -> Self {
        self.include_thread = include;
        self
    }

    /// Sets whether to include module information.
    pub fn with_module(mut self, include: bool) -> Self {
        self.include_module = include;
        self
    }
}

impl Formatter for JsonFormatter {
    fn format(&self, record: &LogRecord) -> String {
        let mut json_obj = json!({
            "timestamp": record.timestamp.format(&self.datetime_format).to_string(),
            "level": record.level.as_str(),
            "message": record.message,
        });

        // Add module information if requested and available
        if self.include_module {
            if let Some(ref module) = record.module {
                json_obj["module"] = json!(module);
            }
        }

        // Add caller information if requested and available
        if self.include_caller {
            if let Some(ref caller) = record.caller {
                json_obj["caller"] = json!({
                    "file": caller.file,
                    "line": caller.line,
                    "module": caller.module,
                });
            }
        }

        // Add thread information if requested and available
        if self.include_thread {
            if let Some(ref thread) = record.thread {
                json_obj["thread"] = json!({
                    "id": thread.id,
                    "name": thread.name,
                });
            }
        }

        // Add custom metadata
        if !record.metadata.is_empty() {
            json_obj["metadata"] = json!(record.metadata);
        }

        if self.pretty {
            serde_json::to_string_pretty(&json_obj).unwrap_or_else(|_| "{}".to_string())
        } else {
            serde_json::to_string(&json_obj).unwrap_or_else(|_| "{}".to_string())
        }
    }
}

/// Plain text formatter without any colors or special formatting.
#[derive(Debug, Clone)]
pub struct PlainFormatter {
    /// DateTime format string
    pub datetime_format: String,
    /// Whether to include caller information
    pub include_caller: bool,
    /// Whether to include thread information
    pub include_thread: bool,
    /// Whether to include module information
    pub include_module: bool,
}

impl Default for PlainFormatter {
    fn default() -> Self {
        Self {
            datetime_format: "%Y-%m-%d %H:%M:%S".to_string(),
            include_caller: false,
            include_thread: false,
            include_module: false,
        }
    }
}

impl PlainFormatter {
    /// Creates a new plain formatter.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the datetime format.
    pub fn with_datetime_format<S: Into<String>>(mut self, format: S) -> Self {
        self.datetime_format = format.into();
        self
    }

    /// Sets whether to include caller information.
    pub fn with_caller(mut self, include: bool) -> Self {
        self.include_caller = include;
        self
    }

    /// Sets whether to include thread information.
    pub fn with_thread(mut self, include: bool) -> Self {
        self.include_thread = include;
        self
    }

    /// Sets whether to include module information.
    pub fn with_module(mut self, include: bool) -> Self {
        self.include_module = include;
        self
    }
}

impl Formatter for PlainFormatter {
    fn format(&self, record: &LogRecord) -> String {
        let timestamp = record.timestamp.format(&self.datetime_format);

        let mut parts = vec![
            format!("{}", timestamp),
            format!("[{}]:", record.level.as_str()),
        ];

        // Add thread information if requested
        if self.include_thread {
            if let Some(ref thread) = record.thread {
                let thread_info = if let Some(ref name) = thread.name {
                    format!("[{}:{}]", name, thread.id)
                } else {
                    format!("[{}]", thread.id)
                };
                parts.push(thread_info);
            }
        }

        // Add module information if requested
        if self.include_module {
            if let Some(ref module) = record.module {
                parts.push(format!("[{module}]"));
            }
        }

        // Add caller information if requested
        if self.include_caller {
            if let Some(ref caller) = record.caller {
                let caller_info = format!("{}:{}", caller.file, caller.line);
                parts.push(format!("[{caller_info}]"));
            }
        }

        // Add the message
        parts.push(record.message.clone());

        // Add metadata if any
        if !record.metadata.is_empty() {
            let metadata_parts: Vec<String> = record
                .metadata
                .iter()
                .map(|(k, v)| format!("{k}={v}"))
                .collect();
            parts.push(format!("[{}]", metadata_parts.join(", ")));
        }

        parts.join(" ")
    }
}

/// Creates a formatter based on the output format.
pub fn create_formatter(
    format: OutputFormat,
    colors: bool,
    datetime_format: &str,
    include_caller: bool,
    include_thread: bool,
    include_module: bool,
) -> Box<dyn Formatter> {
    match format {
        OutputFormat::Text => Box::new(
            TextFormatter::new()
                .with_colors(colors)
                .with_datetime_format(datetime_format)
                .with_caller(include_caller)
                .with_thread(include_thread)
                .with_module(include_module),
        ),
        OutputFormat::Json => Box::new(
            JsonFormatter::new()
                .with_datetime_format(datetime_format)
                .with_caller(include_caller)
                .with_thread(include_thread)
                .with_module(include_module),
        ),
        OutputFormat::Plain => Box::new(
            PlainFormatter::new()
                .with_datetime_format(datetime_format)
                .with_caller(include_caller)
                .with_thread(include_thread)
                .with_module(include_module),
        ),
    }
}

/// Helper function to get current thread information.
pub fn get_thread_info() -> ThreadInfo {
    let current_thread = std::thread::current();
    ThreadInfo {
        id: format!("{:?}", current_thread.id()),
        name: current_thread.name().map(|s| s.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_text_formatter() {
        let formatter = TextFormatter::new().with_colors(false);
        let record = LogRecord::new(LogLevel::Info, format_args!("Test message"));

        let output = formatter.format(&record);
        assert!(output.contains("[ INFO  ]:"));
        assert!(output.contains("Test message"));
    }

    #[test]
    fn test_json_formatter() {
        let formatter = JsonFormatter::new();
        let record = LogRecord::new(LogLevel::Error, format_args!("Error message"));

        let output = formatter.format(&record);
        let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();

        assert_eq!(parsed["level"], "ERROR");
        assert_eq!(parsed["message"], "Error message");
        assert!(parsed["timestamp"].is_string());
    }

    #[test]
    fn test_plain_formatter() {
        let formatter = PlainFormatter::new();
        let record = LogRecord::new(LogLevel::Warning, format_args!("Warning message"));

        let output = formatter.format(&record);
        assert!(output.contains("[WARNING]:"));
        assert!(output.contains("Warning message"));
        assert!(!output.contains("\x1b")); // No ANSI codes
    }

    #[test]
    fn test_formatter_with_metadata() {
        let formatter = TextFormatter::new().with_colors(false);
        let record = LogRecord::new(LogLevel::Debug, format_args!("Debug message"))
            .with_metadata("user_id", "123")
            .with_metadata("request_id", "abc-def");

        let output = formatter.format(&record);
        assert!(output.contains("Debug message"));
        assert!(output.contains("user_id=123"));
        assert!(output.contains("request_id=abc-def"));
    }

    #[test]
    fn test_formatter_with_caller() {
        let formatter = TextFormatter::new().with_colors(false).with_caller(true);

        let caller = CallerInfo {
            file: "test.rs",
            line: 42,
            module: Some("test_module"),
        };

        let record =
            LogRecord::new(LogLevel::Info, format_args!("Test message")).with_caller(caller);

        let output = formatter.format(&record);
        assert!(output.contains("test.rs:42"));
    }
}