inklog 0.2.0

Enterprise-grade Rust logging infrastructure
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
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
use super::LogSink;
use crate::ConsoleSinkConfig;
use crate::DataMasker;
use crate::InklogError;
use crate::LogRecord;
use crate::LogTemplate;
use crate::support::processing::OutputFormat;
use async_trait::async_trait;
use is_terminal::IsTerminal;
use owo_colors::OwoColorize;
use std::fmt;
use std::io::{self, Write};
use std::sync::{Arc, Mutex};

pub struct ConsoleSink {
    config: ConsoleSinkConfig,
    writer: Arc<Mutex<Box<dyn Write + Send>>>,
    template: LogTemplate,
    masker: DataMasker,
}

impl fmt::Debug for ConsoleSink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ConsoleSink")
            .field("config", &self.config)
            .field("template", &self.template)
            .finish()
    }
}

impl ConsoleSink {
    pub fn new(config: ConsoleSinkConfig, template: LogTemplate) -> Self {
        Self {
            config,
            writer: Arc::new(Mutex::new(Box::new(io::stdout()))),
            template,
            masker: DataMasker::new(),
        }
    }

    fn write_record<W: Write>(
        &self,
        writer: &mut W,
        record: &LogRecord,
        use_color: bool,
    ) -> io::Result<()> {
        if self.config.output_format == OutputFormat::Json {
            // JSON mode: serialize the full record, no color
            let json = serde_json::to_string(record).map_err(io::Error::other)?;
            writeln!(writer, "{}", json)
        } else {
            let formatted_message = self.template.render(record);

            if use_color {
                writeln!(
                    writer,
                    "{}",
                    self.apply_color(&formatted_message, &record.level)
                )
            } else {
                writeln!(writer, "{}", formatted_message)
            }
        }
    }

    fn apply_color(&self, message: &str, level: &str) -> String {
        match level {
            "ERROR" | "error" => message.red().to_string(),
            "WARN" | "warn" => message.yellow().to_string(),
            "INFO" | "info" => message.green().to_string(),
            "DEBUG" | "debug" => message.blue().to_string(),
            "TRACE" | "trace" => message.magenta().to_string(),
            _ => message.green().to_string(),
        }
    }

    fn should_colorize(&self, is_stderr: bool) -> bool {
        // JSON mode never uses color (would corrupt JSON structure)
        if self.config.output_format == OutputFormat::Json {
            return false;
        }
        if !self.config.colored {
            return false;
        }

        // NO_COLOR standard (https://no-color.org/)
        if std::env::var("NO_COLOR").is_ok() {
            return false;
        }

        // FORCE_COLOR standard
        if let Ok(val) = std::env::var("CLICOLOR_FORCE")
            && val != "0"
        {
            return true;
        }

        // TERM=dumb
        if let Ok(term) = std::env::var("TERM")
            && term == "dumb"
        {
            return false;
        }

        if is_stderr {
            io::stderr().is_terminal()
        } else {
            io::stdout().is_terminal()
        }
    }
}

#[async_trait]
impl LogSink for ConsoleSink {
    async fn write(&self, record: &LogRecord) -> Result<(), InklogError> {
        // 应用数据脱敏(如果启用)
        let masked_record = if self.config.masking_enabled {
            let mut masked = record.clone();
            masked.message = self.masker.mask(&record.message);
            self.masker.mask_hashmap(&mut masked.fields);
            masked
        } else {
            record.clone()
        };

        // Stderr separation
        let is_stderr = self
            .config
            .stderr_levels
            .contains(&masked_record.level.to_lowercase());

        let use_color = self.should_colorize(is_stderr);

        if is_stderr {
            let mut stderr = io::stderr();
            self.write_record(&mut stderr, &masked_record, use_color)
                .map_err(InklogError::IoError)?;
        } else {
            let mut writer = self
                .writer
                .lock()
                .map_err(|_| InklogError::IoError(io::Error::other("Lock poisoned")))?;
            self.write_record(&mut *writer, &masked_record, use_color)
                .map_err(InklogError::IoError)?;
        }

        Ok(())
    }

    async fn flush(&self) -> Result<(), InklogError> {
        // Flush stdout writer
        let mut writer = self
            .writer
            .lock()
            .map_err(|_| InklogError::IoError(io::Error::other("Lock poisoned")))?;
        writer.flush().map_err(InklogError::IoError)?;
        // Also flush stderr to ensure all output is written
        io::stderr().flush().map_err(InklogError::IoError)
    }

    fn is_healthy(&self) -> bool {
        true
    }

    async fn shutdown(&self) -> Result<(), InklogError> {
        self.flush().await
    }
}

impl Clone for ConsoleSink {
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            // Clone shares the same writer (Arc ensures reference counting)
            writer: Arc::clone(&self.writer),
            template: self.template.clone(),
            // Note: Clone creates a fresh DataMasker instance. Any learned state
            // (e.g., dynamically added patterns) from the original masker is not shared.
            // This is intentional: each cloned sink gets independent masking configuration.
            masker: DataMasker::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ConsoleSinkConfig;
    use serial_test::serial;
    use std::env;

    fn get_sink() -> ConsoleSink {
        ConsoleSink::new(
            ConsoleSinkConfig {
                enabled: true,
                colored: true,
                ..Default::default()
            },
            LogTemplate::default(),
        )
    }

    #[test]
    #[serial]
    fn test_no_color_env() {
        let sink = get_sink();
        unsafe {
            env::set_var("NO_COLOR", "1");
        }
        assert!(!sink.should_colorize(false));
        unsafe {
            env::remove_var("NO_COLOR");
        }
    }

    #[test]
    #[serial]
    fn test_force_color_env() {
        let sink = get_sink();
        // Remove NO_COLOR to ensure deterministic test result
        unsafe {
            env::remove_var("NO_COLOR");
        }
        unsafe {
            env::set_var("CLICOLOR_FORCE", "1");
        }
        assert!(sink.should_colorize(false));
        unsafe {
            env::remove_var("CLICOLOR_FORCE");
        }
    }

    #[test]
    #[serial]
    fn test_term_dumb() {
        let sink = get_sink();
        // Remove NO_COLOR to ensure deterministic test result
        unsafe {
            env::remove_var("NO_COLOR");
        }
        unsafe {
            env::set_var("TERM", "dumb");
        }
        // Ensure no other conflicting envs
        unsafe {
            env::remove_var("CLICOLOR_FORCE");
        }
        assert!(!sink.should_colorize(false));
        unsafe {
            env::remove_var("TERM");
        }
    }

    #[test]
    #[serial]
    fn test_config_disabled() {
        let mut sink = get_sink();
        // Remove NO_COLOR to ensure deterministic test result
        unsafe {
            env::remove_var("NO_COLOR");
        }
        sink.config.colored = false;
        unsafe {
            env::set_var("CLICOLOR_FORCE", "1");
        } // Config should override force?
        // My logic: if !config.colored return false.
        assert!(!sink.should_colorize(false));
        unsafe {
            env::remove_var("CLICOLOR_FORCE");
        }
    }

    #[test]
    fn test_console_sink_new() {
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: true,
            ..Default::default()
        };
        let template = LogTemplate::default();
        let sink = ConsoleSink::new(config, template);
        assert!(sink.config.enabled);
    }

    #[test]
    fn test_console_sink_disabled() {
        let config = ConsoleSinkConfig {
            enabled: false,
            colored: true,
            ..Default::default()
        };
        let template = LogTemplate::default();
        let sink = ConsoleSink::new(config, template);
        assert!(!sink.config.enabled);
    }

    #[test]
    #[serial]
    fn test_should_colorize_defaults() {
        unsafe {
            env::remove_var("CLICOLOR_FORCE");
        }
        unsafe {
            env::remove_var("TERM");
        }
        unsafe {
            env::set_var("NO_COLOR", "1");
        }
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: true,
            ..Default::default()
        };
        let template = LogTemplate::default();
        let sink = ConsoleSink::new(config, template);
        let result = sink.should_colorize(false);
        assert!(
            !result,
            "should_colorize should return false when NO_COLOR is set"
        );
        unsafe {
            env::remove_var("NO_COLOR");
        }
    }

    #[test]
    fn test_should_colorize_when_allowed() {
        let sink = get_sink();
        let colored = sink.apply_color("test message", "ERROR");
        assert!(colored.contains("test message"));
    }

    #[test]
    fn test_apply_color_info() {
        let sink = get_sink();
        let colored = sink.apply_color("test message", "INFO");
        assert!(colored.contains("test message"));
    }

    #[test]
    fn test_apply_color_unknown() {
        let sink = get_sink();
        let colored = sink.apply_color("test message", "UNKNOWN");
        assert!(colored.contains("test message"));
    }

    // ========================================================================
    // Test helpers
    // ========================================================================

    /// A Write implementation that buffers output for inspection in tests.
    #[derive(Default, Clone)]
    struct TestWriter {
        buf: Arc<Mutex<Vec<u8>>>,
    }

    impl Write for TestWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.buf.lock().unwrap().write(buf)
        }
        fn flush(&mut self) -> io::Result<()> {
            self.buf.lock().unwrap().flush()
        }
    }

    impl TestWriter {
        fn output(&self) -> String {
            let buf = self.buf.lock().unwrap();
            String::from_utf8_lossy(&buf).to_string()
        }

        fn is_empty(&self) -> bool {
            self.buf.lock().unwrap().is_empty()
        }
    }

    /// A Write implementation that always fails, for error-path testing.
    struct FailingWriter;

    impl Write for FailingWriter {
        fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
            Err(io::Error::other("write failed"))
        }
        fn flush(&mut self) -> io::Result<()> {
            Err(io::Error::other("flush failed"))
        }
    }

    /// Creates a LogRecord with the given level and message, with sane defaults.
    fn make_record(level: &str, message: &str) -> LogRecord {
        LogRecord {
            level: level.to_string(),
            message: message.to_string(),
            target: "test::module".to_string(),
            ..Default::default()
        }
    }

    /// Creates a ConsoleSink wired to a TestWriter for output inspection.
    /// Returns (sink, writer) so tests can assert on the captured output.
    fn sink_with_test_writer(config: ConsoleSinkConfig) -> (ConsoleSink, TestWriter) {
        let writer = TestWriter::default();
        let mut sink = ConsoleSink::new(config, LogTemplate::default());
        sink.writer = Arc::new(Mutex::new(Box::new(writer.clone())));
        (sink, writer)
    }

    // ========================================================================
    // apply_color: cover remaining branches (WARN, DEBUG, TRACE, lowercase)
    // ========================================================================

    #[test]
    fn test_apply_color_warn() {
        let sink = get_sink();
        let colored = sink.apply_color("warn message", "WARN");
        assert!(colored.contains("warn message"));
    }

    #[test]
    fn test_apply_color_debug() {
        let sink = get_sink();
        let colored = sink.apply_color("debug message", "DEBUG");
        assert!(colored.contains("debug message"));
    }

    #[test]
    fn test_apply_color_trace() {
        let sink = get_sink();
        let colored = sink.apply_color("trace message", "TRACE");
        assert!(colored.contains("trace message"));
    }

    #[test]
    fn test_apply_color_lowercase_levels() {
        let sink = get_sink();
        // Covers lowercase branches ("error", "warn", "info", "debug", "trace")
        // in apply_color's match arms.
        for level in &["error", "warn", "info", "debug", "trace"] {
            let colored = sink.apply_color("payload", level);
            assert!(colored.contains("payload"), "level {} lost message", level);
        }
    }

    #[test]
    #[serial]
    fn test_apply_color_emits_ansi_codes() {
        // Force color emission regardless of terminal detection so we can
        // verify the actual color mapping is correct.
        owo_colors::set_override(true);
        let sink = get_sink();

        let red = sink.apply_color("msg", "ERROR");
        let yellow = sink.apply_color("msg", "WARN");
        let green = sink.apply_color("msg", "INFO");
        let blue = sink.apply_color("msg", "DEBUG");
        let magenta = sink.apply_color("msg", "TRACE");

        // Unset before assertions so global state is clean even if an
        // assertion fails.
        owo_colors::unset_override();

        assert!(
            red.contains("\x1b[31m"),
            "ERROR must be red, got: {:?}",
            red
        );
        assert!(
            yellow.contains("\x1b[33m"),
            "WARN must be yellow, got: {:?}",
            yellow
        );
        assert!(
            green.contains("\x1b[32m"),
            "INFO must be green, got: {:?}",
            green
        );
        assert!(
            blue.contains("\x1b[34m"),
            "DEBUG must be blue, got: {:?}",
            blue
        );
        assert!(
            magenta.contains("\x1b[35m"),
            "TRACE must be magenta, got: {:?}",
            magenta
        );
    }

    // ========================================================================
    // write_record: cover use_color true/false, all level branches, errors
    // ========================================================================

    #[test]
    fn test_write_record_without_color() {
        let sink = get_sink();
        let mut buf: Vec<u8> = Vec::new();
        let record = make_record("INFO", "hello world");
        sink.write_record(&mut buf, &record, false).unwrap();
        let output = String::from_utf8(buf).unwrap();
        // Formatted by default template: {timestamp} [{level}] {target} - {message}
        assert!(output.contains("[INFO]"));
        assert!(output.contains("test::module"));
        assert!(output.contains("hello world"));
        assert!(output.ends_with('\n'), "writeln should append newline");
        // No ANSI escape codes when color is off.
        assert!(!output.contains('\x1b'));
    }

    #[test]
    fn test_write_record_with_color_error() {
        let sink = get_sink();
        let mut buf: Vec<u8> = Vec::new();
        let record = make_record("ERROR", "boom");
        sink.write_record(&mut buf, &record, true).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("boom"));
        assert!(output.contains("[ERROR]"));
        assert!(output.ends_with('\n'));
    }

    #[test]
    fn test_write_record_with_color_warn() {
        let sink = get_sink();
        let mut buf: Vec<u8> = Vec::new();
        let record = make_record("WARN", "careful");
        sink.write_record(&mut buf, &record, true).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("careful"));
        assert!(output.contains("[WARN]"));
    }

    #[test]
    fn test_write_record_with_color_debug() {
        let sink = get_sink();
        let mut buf: Vec<u8> = Vec::new();
        let record = make_record("DEBUG", "details");
        sink.write_record(&mut buf, &record, true).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("details"));
        assert!(output.contains("[DEBUG]"));
    }

    #[test]
    fn test_write_record_with_color_trace() {
        let sink = get_sink();
        let mut buf: Vec<u8> = Vec::new();
        let record = make_record("TRACE", "verbose");
        sink.write_record(&mut buf, &record, true).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("verbose"));
        assert!(output.contains("[TRACE]"));
    }

    #[test]
    fn test_write_record_with_color_unknown_level() {
        // Covers the `_ => record.level.clone()` fallback arm in write_record's
        // level_colored match.
        let sink = get_sink();
        let mut buf: Vec<u8> = Vec::new();
        let record = make_record("FATAL", "critical");
        sink.write_record(&mut buf, &record, true).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("critical"));
        assert!(output.contains("[FATAL]"));
        assert!(output.ends_with('\n'));
    }

    #[test]
    fn test_write_record_lowercase_level_with_color() {
        // Lowercase level strings should also match color branches.
        let sink = get_sink();
        let mut buf: Vec<u8> = Vec::new();
        let record = make_record("error", "lowercase boom");
        sink.write_record(&mut buf, &record, true).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("lowercase boom"));
        assert!(output.contains("[error]"));
    }

    #[test]
    fn test_write_record_propagates_write_error() {
        let sink = get_sink();
        let mut writer = FailingWriter;
        let record = make_record("INFO", "will fail");
        let result = sink.write_record(&mut writer, &record, false);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("write failed"),
            "error should carry the underlying message, got: {}",
            err
        );
    }

    // ========================================================================
    // should_colorize: cover CLICOLOR_FORCE=0 and is_stderr=true branches
    // ========================================================================

    #[test]
    #[serial]
    fn test_should_colorize_clicolor_force_zero_falls_through() {
        // CLICOLOR_FORCE=0 means "do not force", so it should fall through to
        // the TERM check. Setting TERM=dumb makes the result deterministically
        // false, exercising the val != "0" false branch.
        unsafe {
            env::remove_var("NO_COLOR");
        }
        unsafe {
            env::set_var("CLICOLOR_FORCE", "0");
        }
        unsafe {
            env::set_var("TERM", "dumb");
        }
        let sink = get_sink();
        assert!(!sink.should_colorize(false));
        unsafe {
            env::remove_var("CLICOLOR_FORCE");
        }
        unsafe {
            env::remove_var("TERM");
        }
    }

    #[test]
    #[serial]
    fn test_should_colorize_stderr_path_with_force() {
        // CLICOLOR_FORCE=1 forces true, exercising the is_stderr=true branch
        // of the final terminal check (short-circuited by the force).
        unsafe {
            env::remove_var("NO_COLOR");
        }
        unsafe {
            env::set_var("CLICOLOR_FORCE", "1");
        }
        let sink = get_sink();
        assert!(sink.should_colorize(true));
        unsafe {
            env::remove_var("CLICOLOR_FORCE");
        }
    }

    #[test]
    #[serial]
    fn test_should_colorize_term_not_dumb_falls_through() {
        // TERM set to a non-dumb value exercises the `term == "dumb"` false
        // branch. Combined with CLICOLOR_FORCE=1 to make the result
        // deterministically true.
        unsafe {
            env::remove_var("NO_COLOR");
        }
        unsafe {
            env::set_var("TERM", "xterm-256color");
        }
        unsafe {
            env::set_var("CLICOLOR_FORCE", "1");
        }
        let sink = get_sink();
        assert!(sink.should_colorize(false));
        unsafe {
            env::remove_var("TERM");
        }
        unsafe {
            env::remove_var("CLICOLOR_FORCE");
        }
    }

    // ========================================================================
    // LogSink::write: masking, stderr/stdout routing, color interaction
    // ========================================================================

    #[tokio::test]
    async fn test_log_sink_write_stdout_no_masking() {
        // masking_enabled=false covers the `else` branch of the masking if/else.
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: false,
            masking_enabled: false,
            ..Default::default()
        };
        let (sink, writer) = sink_with_test_writer(config);
        let record = make_record("INFO", "plain message");
        sink.write(&record).await.unwrap();
        let output = writer.output();
        assert!(output.contains("plain message"));
        assert!(output.contains("[INFO]"));
        assert!(output.ends_with('\n'));
    }

    #[tokio::test]
    async fn test_log_sink_write_with_masking_redacts_sensitive_data() {
        // masking_enabled=true covers the `if` branch: mask message + fields.
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: false,
            masking_enabled: true,
            ..Default::default()
        };
        let (sink, writer) = sink_with_test_writer(config);
        let record = make_record("INFO", "email=test@example.com");
        sink.write(&record).await.unwrap();
        let output = writer.output();
        // Original sensitive data must not appear.
        assert!(
            !output.contains("test@example.com"),
            "masked output must not contain the original email, got: {}",
            output
        );
        // Masked email retains the @ separator (partial masking pattern).
        assert!(output.contains('@'), "masked email should retain @");
    }

    #[tokio::test]
    async fn test_log_sink_write_stderr_level_writes_to_stderr_not_stdout() {
        // is_stderr=true in write() routes to io::stderr(), so the stdout
        // TestWriter should remain empty.
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: false,
            stderr_levels: vec!["error".to_string()],
            ..Default::default()
        };
        let (sink, writer) = sink_with_test_writer(config);
        let record = make_record("ERROR", "stderr-only message");
        sink.write(&record).await.unwrap();
        assert!(
            writer.is_empty(),
            "stdout writer must be empty when level routes to stderr"
        );
    }

    #[tokio::test]
    async fn test_log_sink_write_warn_routes_to_stderr_by_default() {
        // Default stderr_levels is ["error", "warn"]; WARN should go to stderr.
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: false,
            ..Default::default()
        };
        let (sink, writer) = sink_with_test_writer(config);
        let record = make_record("WARN", "warning via stderr");
        sink.write(&record).await.unwrap();
        assert!(
            writer.is_empty(),
            "WARN should route to stderr by default, not stdout"
        );
    }

    #[tokio::test]
    async fn test_log_sink_write_info_routes_to_stdout_by_default() {
        // INFO is not in default stderr_levels, so it goes to stdout writer.
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: false,
            ..Default::default()
        };
        let (sink, writer) = sink_with_test_writer(config);
        let record = make_record("INFO", "info via stdout");
        sink.write(&record).await.unwrap();
        let output = writer.output();
        assert!(output.contains("info via stdout"));
    }

    #[tokio::test]
    async fn test_log_sink_write_case_insensitive_stderr_match() {
        // stderr_levels contains lowercase "error"; record level "ERROR"
        // should still match after to_lowercase().
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: false,
            stderr_levels: vec!["error".to_string()],
            ..Default::default()
        };
        let (sink, writer) = sink_with_test_writer(config);
        let record = make_record("ERROR", "uppercase level");
        sink.write(&record).await.unwrap();
        assert!(
            writer.is_empty(),
            "uppercase ERROR must match lowercase stderr_levels"
        );
    }

    // ========================================================================
    // LogSink trait: flush, is_healthy, shutdown
    // ========================================================================

    #[tokio::test]
    async fn test_log_sink_flush_succeeds() {
        let (sink, _writer) = sink_with_test_writer(ConsoleSinkConfig::default());
        assert!(sink.flush().await.is_ok());
    }

    #[test]
    fn test_log_sink_is_healthy_always_true() {
        let sink = get_sink();
        // ConsoleSink is always healthy (no persistent state to fail).
        assert!(sink.is_healthy());
    }

    #[tokio::test]
    async fn test_log_sink_shutdown_flushes_without_error() {
        let (sink, _writer) = sink_with_test_writer(ConsoleSinkConfig::default());
        // shutdown delegates to flush, so it should succeed.
        assert!(sink.shutdown().await.is_ok());
    }

    // ========================================================================
    // Clone impl: config preserved, writer shared via Arc
    // ========================================================================

    #[test]
    fn test_console_sink_clone_preserves_config() {
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: true,
            stderr_levels: vec!["error".to_string(), "warn".to_string()],
            masking_enabled: true,
            output_format: Default::default(),
        };
        let sink = ConsoleSink::new(config, LogTemplate::default());
        let cloned = sink.clone();
        assert!(cloned.config.enabled);
        assert!(cloned.config.colored);
        assert!(cloned.config.masking_enabled);
        assert_eq!(cloned.config.stderr_levels, vec!["error", "warn"]);
        // Both original and clone should remain healthy.
        assert!(sink.is_healthy());
        assert!(cloned.is_healthy());
    }

    #[tokio::test]
    async fn test_console_sink_clone_shares_writer_buffer() {
        // Arc Clone shares the same underlying writer, so writes via the clone
        // should be visible through the original's writer reference.
        let config = ConsoleSinkConfig {
            enabled: true,
            colored: false,
            ..Default::default()
        };
        let (sink, writer) = sink_with_test_writer(config);
        let cloned = sink.clone();
        let record = make_record("INFO", "written via clone");
        cloned.write(&record).await.unwrap();
        let output = writer.output();
        assert!(
            output.contains("written via clone"),
            "clone shares writer via Arc, output should be visible"
        );
    }

    // ========================================================================
    // Debug impl: only config and template fields
    // ========================================================================

    #[test]
    fn test_console_sink_debug_format() {
        let sink = get_sink();
        let debug_str = format!("{:?}", sink);
        // Debug impl only exposes config and template fields.
        assert!(debug_str.contains("ConsoleSink"));
        assert!(debug_str.contains("config"));
        assert!(debug_str.contains("template"));
        // writer and masker are deliberately omitted by the Debug impl.
        assert!(!debug_str.contains("writer"));
        assert!(!debug_str.contains("masker"));
    }

    // ========================================================================
    // write_record with color: INFO 级别(覆盖 writeln! 着色分支,行 62)
    // ========================================================================

    #[test]
    fn test_write_record_with_color_info() {
        // 显式覆盖 use_color=true 且 level=INFO 的写入路径
        // 现有测试已覆盖 ERROR/WARN/DEBUG/TRACE,新增 INFO 补全 match 分支
        let sink = get_sink();
        let mut buf: Vec<u8> = Vec::new();
        let record = make_record("INFO", "info colored output");
        sink.write_record(&mut buf, &record, true).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("info colored output"));
        assert!(output.contains("[INFO]"));
        assert!(
            output.ends_with('\n'),
            "writeln should append newline, got: {:?}",
            output
        );
    }

    // ========================================================================
    // write_record with color: 错误路径(覆盖行 62 writeln! 失败分支)
    // ========================================================================

    #[test]
    fn test_write_record_with_color_propagates_write_error() {
        // 覆盖 use_color=true 时 writeln! 失败的分支(行 61-65)
        // 现有 test_write_record_propagates_write_error 只覆盖 use_color=false
        let sink = get_sink();
        let mut writer = FailingWriter;
        let record = make_record("ERROR", "colored but fails");
        let result = sink.write_record(&mut writer, &record, true);
        assert!(
            result.is_err(),
            "write_record with color should propagate error"
        );
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("write failed"),
            "error should carry the underlying message, got: {}",
            err
        );
    }

    #[test]
    fn test_write_record_with_color_all_levels_propagate_error() {
        // 覆盖 use_color=true 时各 level 着色后 writeln! 失败的分支
        // 确保 match 各分支后的 writeln! 都能传播错误
        let sink = get_sink();
        for level in &["ERROR", "WARN", "INFO", "DEBUG", "TRACE", "FATAL"] {
            let mut writer = FailingWriter;
            let record = make_record(level, "payload");
            let result = sink.write_record(&mut writer, &record, true);
            assert!(
                result.is_err(),
                "write_record with color should fail for level: {}",
                level
            );
        }
    }
}