inklog 0.3.0-rc.1

Enterprise-grade Rust logging infrastructure
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! # 日志模板模块
//!
//! 提供自定义日志格式化和字段提取功能,支持灵活的日志消息模板配置。
//!
//! ## 概述
//!
//! `LogTemplate` 结构体实现日志消息的模板化渲染,支持自定义占位符和格式。
//! 通过模板系统,可以灵活控制日志输出的格式和内容。

use crate::LogRecord;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt;
use std::str::FromStr;

fn format_field(key: &str, value: &Value) -> String {
    match value {
        // Strings: render without JSON quotes for human-readable output
        Value::String(s) => format!("{}={}", key, s),
        // Array/Object use JSON serialization (Display for these is JSON anyway)
        other => format!("{}={}", key, other),
    }
}

/// Output format for log sinks.
///
/// Controls whether logs are rendered as human-readable text (via `LogTemplate`)
/// or as machine-parseable JSON (one object per line).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
    /// Human-readable text using `LogTemplate`.
    #[default]
    Text,
    /// Newline-Delimited JSON (NDJSON).
    Json,
}

impl fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Text => write!(f, "text"),
            Self::Json => write!(f, "json"),
        }
    }
}

impl FromStr for OutputFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "text" => Ok(Self::Text),
            "json" => Ok(Self::Json),
            other => Err(format!(
                "unknown output format: '{}', expected 'text' or 'json'",
                other
            )),
        }
    }
}

/// Template-based log message formatter with customizable placeholders.
///
/// `LogTemplate` provides flexible log message formatting through template strings
/// with placeholders that are replaced with values from [`LogRecord`].
///
/// # Supported Placeholders
///
/// | Placeholder | Description | Example Output |
/// |-------------|-------------|----------------|
/// | `{timestamp}` | UTC timestamp in ISO 8601 format | `2026-03-19T10:30:45.123Z` |
/// | `{level}` | Log level | `INFO`, `ERROR`, `DEBUG` |
/// | `{target}` | Target module path | `my_module::submodule` |
/// | `{message}` | Log message content | `User logged in` |
/// | `{file}` | Source file path | `src/main.rs` |
/// | `{line}` | Line number in source file | `42` |
/// | `{thread_id}` | Thread identifier | `thread-1` |
/// | `{fields}` | Structured fields as key=value pairs | `user=123 action=login` |
///
/// # Escaping
///
/// To include literal braces in the output, use `{{` and `}}`:
/// - Template: `{{literal}} {message}`
/// - Output: `{literal} User logged in`
///
/// # Examples
///
/// ```
/// use inklog::template::LogTemplate;
/// use inklog::log_record::LogRecord;
/// use chrono::Utc;
/// use std::collections::HashMap;
/// use serde_json::Value;
///
/// // Create a template with standard format
/// let template = LogTemplate::new("{timestamp} [{level}] {target} - {message}");
///
/// // Render a log record
/// let record = LogRecord {
///     timestamp: Utc::now(),
///     level: "INFO".to_string(),
///     target: "my_app::api".to_string(),
///     message: "Request processed".to_string(),
///     fields: HashMap::new(),
///     file: None,
///     line: None,
///     thread_id: "main".to_string(),
/// };
///
/// let output = template.render(&record);
/// // Output: "2026-03-19T10:30:45.123Z [INFO] my_app::api - Request processed"
/// ```
///
/// # Performance
///
/// Template parsing happens once during [`LogTemplate::new()`], and the parsed
/// placeholder structure is reused for all subsequent [`render()`](LogTemplate::render)
/// calls, making rendering efficient for high-throughput logging scenarios.
#[derive(Debug, Clone)]
pub struct LogTemplate {
    placeholders: Vec<Placeholder>,
}

#[derive(Debug, Clone)]
enum Placeholder {
    Timestamp,
    Level,
    Target,
    Message,
    File,
    Line,
    ThreadId,
    Fields,
    Literal(String),
}

impl LogTemplate {
    /// Creates a new `LogTemplate` from a template string.
    ///
    /// Parses the template string to identify placeholders (enclosed in `{}`) and
    /// literal text. The parsed structure is stored for efficient rendering.
    ///
    /// # Arguments
    ///
    /// * `template` - A template string containing placeholders and literal text.
    ///   Placeholders are enclosed in curly braces: `{placeholder_name}`.
    ///
    /// # Supported Placeholders
    ///
    /// - `{timestamp}` - UTC timestamp (ISO 8601 format with milliseconds)
    /// - `{level}` - Log level (INFO, ERROR, DEBUG, etc.)
    /// - `{target}` - Target module path
    /// - `{message}` - Log message content
    /// - `{file}` - Source file path (optional, renders empty if not present)
    /// - `{line}` - Line number (optional, renders empty if not present)
    /// - `{thread_id}` - Thread identifier
    /// - `{fields}` - Structured fields as `key=value` pairs
    ///
    /// # Escaping
    ///
    /// Use `{{` to output a literal `{` character:
    /// - Input: `"{{escaped}}"` → Output: `"{escaped}"`
    ///
    /// Unknown placeholders are rendered as-is (e.g., `{unknown}` remains `{unknown}`).
    ///
    /// # Examples
    ///
    /// ```
    /// use inklog::template::LogTemplate;
    ///
    /// // Standard log format
    /// let template = LogTemplate::new("{timestamp} [{level}] {target} - {message}");
    ///
    /// // With file and line information
    /// let template = LogTemplate::new("{message} ({file}:{line})");
    ///
    /// // Custom format with fields
    /// let template = LogTemplate::new("[{level}] {message} {fields}");
    ///
    /// // With literal braces
    /// let template = LogTemplate::new("{{literal}} {message}");
    /// ```
    pub fn new(template: &str) -> Self {
        let mut placeholders = Vec::new();
        let mut current = String::new();
        let mut in_placeholder = false;
        let chars: Vec<char> = template.chars().collect();

        let mut i = 0;
        while i < chars.len() {
            let ch = chars[i];

            if ch == '{' {
                // Check for escaped brace {{
                if i + 1 < chars.len() && chars[i + 1] == '{' {
                    // Double brace escape: {{ becomes {
                    current.push('{');
                    i += 2;
                    continue;
                }

                if !current.is_empty() {
                    placeholders.push(Placeholder::Literal(current.clone()));
                    current.clear();
                }
                in_placeholder = true;
                i += 1;
            } else if ch == '}' {
                // Check for escaped brace }}
                if i + 1 < chars.len() && chars[i + 1] == '}' {
                    // Double brace escape: }} becomes }
                    current.push('}');
                    i += 2;
                    continue;
                }

                if in_placeholder {
                    let placeholder_name = current.trim().to_lowercase();
                    match placeholder_name.as_str() {
                        "timestamp" => placeholders.push(Placeholder::Timestamp),
                        "level" => placeholders.push(Placeholder::Level),
                        "target" => placeholders.push(Placeholder::Target),
                        "message" => placeholders.push(Placeholder::Message),
                        "file" => placeholders.push(Placeholder::File),
                        "line" => placeholders.push(Placeholder::Line),
                        "thread_id" => placeholders.push(Placeholder::ThreadId),
                        "fields" => placeholders.push(Placeholder::Fields),
                        _ => {
                            placeholders.push(Placeholder::Literal(format!("{{{}}}", current)));
                        }
                    }
                    current.clear();
                    in_placeholder = false;
                } else {
                    // Literal } outside placeholder
                    current.push(ch);
                }
                i += 1;
            } else {
                current.push(ch);
                i += 1;
            }
        }

        // Don't forget remaining content after last placeholder
        if !current.is_empty() {
            placeholders.push(Placeholder::Literal(current));
        }

        Self { placeholders }
    }

    /// Renders a log record using the template.
    ///
    /// Replaces all placeholders in the template with values from the provided `LogRecord`.
    /// The rendering is efficient as the template is pre-parsed during construction.
    ///
    /// # Arguments
    ///
    /// * `record` - The log record containing values to substitute into the template.
    ///
    /// # Returns
    ///
    /// A formatted string with all placeholders replaced by their corresponding values
    /// from the log record.
    ///
    /// # Placeholder Resolution
    ///
    /// | Placeholder | Source Field | Behavior When Missing |
    /// |-------------|--------------|----------------------|
    /// | `{timestamp}` | `record.timestamp` | Always present (required field) |
    /// | `{level}` | `record.level` | Always present (required field) |
    /// | `{target}` | `record.target` | Always present (required field) |
    /// | `{message}` | `record.message` | Always present (required field) |
    /// | `{file}` | `record.file` | Renders as empty string if `None` |
    /// | `{line}` | `record.line` | Renders as empty string if `None` |
    /// | `{thread_id}` | `record.thread_id` | Always present (required field) |
    /// | `{fields}` | `record.fields` | Renders as empty string if empty |
    ///
    /// # Examples
    ///
    /// ```
    /// use inklog::template::LogTemplate;
    /// use inklog::log_record::LogRecord;
    /// use chrono::Utc;
    /// use std::collections::HashMap;
    ///
    /// let template = LogTemplate::new("[{level}] {message}");
    /// let record = LogRecord {
    ///     timestamp: Utc::now(),
    ///     level: "INFO".to_string(),
    ///     target: "my_module".to_string(),
    ///     message: "Task completed".to_string(),
    ///     fields: HashMap::new(),
    ///     file: None,
    ///     line: None,
    ///     thread_id: "main".to_string(),
    /// };
    ///
    /// let output = template.render(&record);
    /// assert!(output.starts_with("[INFO] Task completed"));
    /// ```
    pub fn render(&self, record: &LogRecord) -> String {
        let mut result = String::new();

        for placeholder in &self.placeholders {
            match placeholder {
                Placeholder::Timestamp => {
                    result.push_str(
                        &record
                            .timestamp
                            .format("%Y-%m-%dT%H:%M:%S%.3fZ")
                            .to_string(),
                    );
                }
                Placeholder::Level => {
                    result.push_str(&record.level);
                }
                Placeholder::Target => {
                    result.push_str(&record.target);
                }
                Placeholder::Message => {
                    result.push_str(&record.message);
                }
                Placeholder::File => {
                    if let Some(ref file) = record.file {
                        result.push_str(file);
                    }
                }
                Placeholder::Line => {
                    if let Some(line) = record.line {
                        result.push_str(&line.to_string());
                    }
                }
                Placeholder::ThreadId => {
                    result.push_str(&record.thread_id);
                }
                Placeholder::Fields => {
                    if !record.fields.is_empty() {
                        result.push(' ');
                        let fields_str = record
                            .fields
                            .iter()
                            .map(|(k, v)| format_field(k, v))
                            .collect::<Vec<_>>()
                            .join(" ");
                        result.push_str(&fields_str);
                    }
                }
                Placeholder::Literal(lit) => {
                    result.push_str(lit);
                }
            }
        }

        result
    }
}

impl Default for LogTemplate {
    fn default() -> Self {
        Self::new("{timestamp} [{level}] {target} - {message}")
    }
}

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

    use crate::LogRecord;
    use chrono::Utc;
    use serde_json::Value;
    use std::collections::HashMap;

    fn create_test_record() -> LogRecord {
        LogRecord {
            timestamp: Utc::now(),
            level: "INFO".to_string(),
            target: "test_module".to_string(),
            message: "Test message".to_string(),
            fields: HashMap::from([
                ("user".to_string(), Value::String("123".to_string())),
                ("action".to_string(), Value::String("login".to_string())),
            ]),
            file: Some("/path/to/test.rs".to_string()),
            line: Some(42),
            thread_id: "abc123".to_string(),
        }
    }

    #[test]
    fn test_default_format() {
        let template = LogTemplate::default();
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.contains("INFO"));
        assert!(output.contains("test_module"));
        assert!(output.contains("Test message"));
    }

    #[test]
    fn test_custom_format() {
        let template = LogTemplate::new("[{timestamp}] [{level}] {message}");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.starts_with("["));
        assert!(output.contains("] [INFO] Test message"));
    }

    #[test]
    fn test_all_placeholders() {
        let template =
            LogTemplate::new("{timestamp} [{level}] {target} - {message} ({file}:{line})");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.contains("/path/to/test.rs:42"));
    }

    #[test]
    fn test_fields_placeholder() {
        let template = LogTemplate::new("{message} {fields}");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.contains("user=123"), "Output: {}", output);
        assert!(output.contains("action=login"), "Output: {}", output);
    }

    #[test]
    fn test_literal_braces() {
        let template = LogTemplate::new("{{literal}} {message}");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.starts_with("{literal}"));
    }

    #[test]
    fn test_empty_fields() {
        let template = LogTemplate::new("{message}");
        let mut record = create_test_record();
        record.fields.clear();
        let output = template.render(&record);
        assert_eq!(output, "Test message");
    }

    #[test]
    fn test_thread_id_placeholder() {
        let template = LogTemplate::new("{message} [thread:{thread_id}]");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.contains("[thread:abc123]"));
    }

    #[test]
    fn test_unknown_placeholder() {
        let template = LogTemplate::new("{message} {unknown}");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.contains("{unknown}"));
    }

    #[test]
    fn test_literal_closing_brace_outside_placeholder() {
        // Test the branch where a '}' is encountered outside a placeholder (line 204)
        let template = LogTemplate::new("test} {message}");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.contains("test}"));
        assert!(output.contains("Test message"));
    }

    #[test]
    fn test_multiple_literal_closing_braces() {
        // Multiple literal } outside placeholders
        let template = LogTemplate::new("} {message} } end");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.starts_with("}"));
        assert!(output.contains("Test message"));
        assert!(output.contains("} end"));
    }

    #[test]
    fn test_multiple_timestamps() {
        let template = LogTemplate::new("{timestamp} - {timestamp}");
        let record = create_test_record();
        let output = template.render(&record);
        let parts: Vec<&str> = output.split(" - ").collect();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0], parts[1]);
    }

    #[test]
    fn test_special_characters_in_message() {
        let template = LogTemplate::new("{message}");
        let mut record = create_test_record();
        record.message = "Special chars: \"quotes\" & <brackets>".to_string();
        let output = template.render(&record);
        assert!(output.contains("quotes"));
        assert!(output.contains("&"));
        assert!(output.contains("brackets"));
    }

    #[test]
    fn test_numeric_fields() {
        let template = LogTemplate::new("{message} {fields}");
        let mut record = create_test_record();
        record.fields = HashMap::from([
            (
                "count".to_string(),
                Value::Number(serde_json::Number::from(42)),
            ),
            (
                "price".to_string(),
                Value::Number(serde_json::Number::from_f64(19.99).unwrap()),
            ),
        ]);
        let output = template.render(&record);
        assert!(output.contains("count=42"));
        assert!(output.contains("price=19.99"));
    }

    #[test]
    fn test_boolean_fields() {
        let template = LogTemplate::new("{message} {fields}");
        let mut record = create_test_record();
        record.fields = HashMap::from([
            ("active".to_string(), Value::Bool(true)),
            ("deleted".to_string(), Value::Bool(false)),
        ]);
        let output = template.render(&record);
        assert!(output.contains("active=true"));
        assert!(output.contains("deleted=false"));
    }

    #[test]
    fn test_null_fields() {
        let template = LogTemplate::new("{message} {fields}");
        let mut record = create_test_record();
        record.fields = HashMap::from([("optional".to_string(), Value::Null)]);
        let output = template.render(&record);
        assert!(output.contains("optional=null"));
    }

    #[test]
    fn test_empty_line_and_file() {
        let template = LogTemplate::new("{message} ({file}:{line})");
        let mut record = create_test_record();
        record.file = None;
        record.line = None;
        let output = template.render(&record);
        // When both file and line are None, it renders as "(:)"
        assert!(output.contains("Test message"));
    }

    #[test]
    fn test_template_clone() {
        let template1 = LogTemplate::new("{timestamp} [{level}] {message}");
        let template2 = template1.clone();
        let record = create_test_record();
        let output1 = template1.render(&record);
        let output2 = template2.render(&record);
        assert_eq!(output1, output2);
    }

    #[test]
    fn test_escaped_brace() {
        let template = LogTemplate::new(r"{{escaped}} {message}");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.starts_with("{escaped}"));
    }

    #[test]
    fn test_complex_format() {
        let template =
            LogTemplate::new("[{timestamp}] [{level}] [{thread_id}] {target} - {message} {fields}");
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.contains("[INFO]"));
        assert!(output.contains("[abc123]"));
        assert!(output.contains("test_module"));
        assert!(output.contains("user=123"));
        assert!(output.contains("action=login"));
    }

    #[test]
    fn test_deeply_nested_fields() {
        let template = LogTemplate::new("{message} {fields}");
        let mut record = create_test_record();
        let inner = serde_json::json!({"level3": "deep"});
        let middle = serde_json::json!({"level2": inner});
        record.fields = HashMap::from([("level1".to_string(), middle)]);
        let output = template.render(&record);
        assert!(output.contains("level3"));
    }

    #[test]
    fn test_array_in_fields() {
        let template = LogTemplate::new("{message} {fields}");
        let mut record = create_test_record();
        record.fields = HashMap::from([(
            "items".to_string(),
            Value::Array(vec![
                Value::String("a".to_string()),
                Value::String("b".to_string()),
                Value::String("c".to_string()),
            ]),
        )]);
        let output = template.render(&record);
        assert!(output.contains("items"));
        assert!(output.contains("a"));
        assert!(output.contains("b"));
        assert!(output.contains("c"));
    }

    #[test]
    fn test_template_from_str() {
        let template = LogTemplate::new("{timestamp} [{level}] {message}");
        // Verify template parses and renders correctly
        let record = create_test_record();
        let output = template.render(&record);
        assert!(output.contains("INFO"));
        assert!(output.contains("Test message"));
    }

    #[test]
    fn test_target_with_underscores() {
        let template = LogTemplate::new("{target} - {message}");
        let mut record = create_test_record();
        record.target = "my_module.sub_module".to_string();
        let output = template.render(&record);
        assert!(output.contains("my_module.sub_module"));
    }

    #[test]
    fn test_message_with_newlines() {
        let template = LogTemplate::new("{message}");
        let mut record = create_test_record();
        record.message = "Line1\nLine2\nLine3".to_string();
        let output = template.render(&record);
        assert!(output.contains("Line1"));
        assert!(output.contains("Line2"));
        assert!(output.contains("Line3"));
    }

    #[test]
    fn test_timestamp_format() {
        let template = LogTemplate::new("{timestamp}");
        let record = create_test_record();
        let output = template.render(&record);
        // Timestamp should contain numbers
        assert!(output.chars().any(|c| c.is_ascii_digit()));
    }

    #[test]
    fn test_level_display() {
        let template = LogTemplate::new("[{level}] {message}");
        let mut record = create_test_record();
        record.level = "ERROR".to_string();
        let output = template.render(&record);
        assert!(output.contains("[ERROR]"));
    }

    #[test]
    fn test_message_with_unicode() {
        let template = LogTemplate::new("{message}");
        let mut record = create_test_record();
        record.message = "你好世界 🌍 مرحبا".to_string();
        let output = template.render(&record);
        assert!(output.contains("你好世界"));
        assert!(output.contains("مرحبا"));
    }

    #[test]
    fn test_message_with_template_syntax() {
        let template = LogTemplate::new("{message}");
        let mut record = create_test_record();
        record.message = "Value is {variable}".to_string();
        let output = template.render(&record);
        assert!(output.contains("{variable}"));
    }
}