dmsc 0.1.9

Ri - A high-performance Rust middleware framework with modular architecture
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
//!
//! This file is part of Ri.
//! The Ri project belongs to the Dunimd Team.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! You may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//!     http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.

#![allow(non_snake_case)]

//! # Logging System
//! 
//! This module provides a comprehensive logging system for Ri, supporting multiple output formats,
//! log levels, and configurable logging behavior. It includes support for structured logging,
//! distributed tracing integration, and log rotation.
//! 
//! ## Key Components
//! 
//! - **RiLogLevel**: Enum defining supported log levels (Debug, Info, Warn, Error)
//! - **RiLogConfig**: Configuration struct for logging behavior
//! - **RiLogContext**: Thread-local context for adding contextual information to logs
//! - **RiLogger**: Public-facing logger class for application use
//! - **LoggerImpl**: Internal logger implementation
//! 
//! ## Design Principles
//! 
//! 1. **Multiple Outputs**: Supports both console and file logging
//! 2. **Structured Logging**: Supports both text and JSON formats
//! 3. **Distributed Tracing**: Integrates with distributed tracing context
//! 4. **Configurable**: Highly configurable through `RiLogConfig`
//! 5. **Performance**: Includes sampling support for high-volume logging
//! 6. **Log Rotation**: Supports size-based log rotation
//! 7. **Contextual Logging**: Allows adding contextual information to logs
//! 
//! ## Usage
//! 
//! ```rust,ignore
//! use ri::prelude::*;
//! 
//! fn example() -> RiResult<()> {
//!     // Create a default log configuration
//!     let log_config = RiLogConfig::default();
//!     
//!     // Create a file system instance (usually provided by the service context)
//!     let fs = RiFileSystem::new();
//!     
//!     // Create a logger
//!     let logger = RiLogger::new(&log_config, fs);
//!     
//!     // Log messages at different levels
//!     logger.debug("example", "Debug message")?;
//!     logger.info("example", "Info message")?;
//!     logger.warn("example", "Warning message")?;
//!     logger.error("example", "Error message")?;
//!     
//!     Ok(())
//! }
//! ```

// Logging module for Ri.
// This is a first-stage implementation using std only; can be extended later.

use std::fmt::Debug;
use std::sync::{Arc, Mutex, Condvar};
use std::thread;
use std::time::Duration;
use std::collections::VecDeque;

use crate::core::RiResult;
use crate::fs::RiFileSystem;
use rand;
use serde_json::json;
use std::fs as stdfs;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
mod context;
pub use context::RiLogContext;

/// Log level definition.
/// 
/// This enum defines the supported log levels in Ri, ordered by severity from lowest to highest.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass(eq, eq_int))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RiLogLevel {
    /// Debug level: Detailed information for debugging purposes
    Debug,
    /// Info level: General information about application operation
    Info,
    /// Warn level: Warning messages about potential issues
    Warn,
    /// Error level: Error messages about failures
    Error,
}

impl RiLogLevel {
    /// Returns the string representation of the log level.
    /// 
    /// # Returns
    /// 
    /// A static string representing the log level ("DEBUG", "INFO", "WARN", or "ERROR")
    pub fn as_str(&self) -> &'static str {
        match self {
            RiLogLevel::Debug => "DEBUG",
            RiLogLevel::Info => "INFO",
            RiLogLevel::Warn => "WARN",
            RiLogLevel::Error => "ERROR",
        }
    }

    /// Returns the color block emoji for the log level.
    /// 
    /// # Returns
    /// 
    /// A static string representing the color block emoji
    pub fn color_block(&self) -> &'static str {
        match self {
            RiLogLevel::Debug => "🟦",
            RiLogLevel::Info => "🟩",
            RiLogLevel::Warn => "🟨",
            RiLogLevel::Error => "🟥",
        }
    }

    /// Parses a log level from an environment variable.
    /// 
    /// Reads the `Ri_LOG_LEVEL` environment variable and returns the corresponding log level.
    /// If the environment variable is not set or contains an invalid value, returns `None`.
    /// 
    /// # Returns
    /// 
    /// An `Option<RiLogLevel>` containing the parsed log level
    pub fn from_env() -> Option<Self> {
        std::env::var("Ri_LOG_LEVEL").ok().and_then(|s| {
            match s.to_ascii_uppercase().as_str() {
                "DEBUG" => Some(RiLogLevel::Debug),
                "INFO" => Some(RiLogLevel::Info),
                "WARN" | "WARNING" => Some(RiLogLevel::Warn),
                "ERROR" => Some(RiLogLevel::Error),
                _ => None,
            }
        })
    }

    /// Creates a log level from a string.
    /// 
    /// # Parameters
    /// 
    /// - `s`: The string to parse
    /// 
    /// # Returns
    /// 
    /// An `Option<RiLogLevel>` containing the parsed log level
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_ascii_uppercase().as_str() {
            "DEBUG" => Some(RiLogLevel::Debug),
            "INFO" => Some(RiLogLevel::Info),
            "WARN" | "WARNING" => Some(RiLogLevel::Warn),
            "ERROR" => Some(RiLogLevel::Error),
            _ => None,
        }
    }
}

/// Public logging configuration class.
/// 
/// This struct defines the configuration options for the Ri logging system, including
/// log level, output formats, sampling, and log rotation settings.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass(get_all, set_all))]
#[derive(Clone)]
pub struct RiLogConfig {
    /// Minimum log level to be logged
    pub level: RiLogLevel,
    /// Whether console logging is enabled
    pub console_enabled: bool,
    /// Whether file logging is enabled
    pub file_enabled: bool,
    /// Default sampling rate (0.0 to 1.0, where 1.0 means all logs are sampled)
    pub sampling_default: f32,
    /// Name of the log file
    pub file_name: String,
    /// Whether to use JSON format for logs
    pub json_format: bool,
    /// When to rotate logs (currently only "size" or "none" are supported)
    pub rotate_when: String,
    /// Maximum file size in bytes before rotation (used when rotate_when == "size")
    pub max_bytes: u64,
    /// Whether to use color blocks in log output
    pub color_blocks: bool,
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiLogConfig {
    #[new]
    fn py_new() -> Self {
        Self::default()
    }

    #[staticmethod]
    #[pyo3(name = "default")]
    fn default_py() -> Self {
        Self::default()
    }

    #[staticmethod]
    #[pyo3(signature = (level="info", console_enabled=true, file_enabled=false, file_name="ri.log", json_format=false, max_bytes=10485760, color_blocks=true))]
    fn create(
        level: &str,
        console_enabled: bool,
        file_enabled: bool,
        file_name: &str,
        json_format: bool,
        max_bytes: u64,
        color_blocks: bool,
    ) -> Self {
        let log_level = match level.to_uppercase().as_str() {
            "DEBUG" => RiLogLevel::Debug,
            "INFO" => RiLogLevel::Info,
            "WARN" | "WARNING" => RiLogLevel::Warn,
            "ERROR" => RiLogLevel::Error,
            _ => RiLogLevel::Info,
        };
        Self {
            level: log_level,
            console_enabled,
            file_enabled,
            sampling_default: 1.0,
            file_name: file_name.to_string(),
            json_format,
            rotate_when: "size".to_string(),
            max_bytes,
            color_blocks,
        }
    }
}

impl RiLogConfig {
    /// Creates a log configuration from a `RiConfig` instance.
    /// 
    /// This method reads logging configuration from a `RiConfig` instance, using the following keys:
    /// - log.level: Log level (DEBUG, INFO, WARN, ERROR)
    /// - log.console_enabled: Whether console logging is enabled
    /// - log.file_enabled: Whether file logging is enabled
    /// - log.sampling_default: Default sampling rate
    /// - log.file_name: Name of the log file
    /// - log.file_format: Log format ("json" for JSON format, anything else for text)
    /// - log.rotate_when: When to rotate logs
    /// - log.max_bytes: Maximum file size before rotation
    /// 
    /// # Parameters
    /// 
    /// - `config`: The `RiConfig` instance to read from
    /// 
    /// # Returns
    /// 
    /// A `RiLogConfig` instance with configuration from the given `RiConfig`
    pub fn from_config(config: &crate::config::RiConfig) -> Self {
        let mut base = RiLogConfig::default();

        if let Some(level_str) = config.get_str("log.level") {
            if let Some(level) = RiLogLevel::from_str(level_str) {
                base.level = level;
            }
        }

        if let Some(v) = config.get_f32("log.sampling_default") {
            base.sampling_default = v.clamp(0.0, 1.0);
        }

        if let Some(file_name) = config.get_str("log.file_name") {
            if !file_name.is_empty() {
                base.file_name = file_name.to_string();
            }
        }

        if let Some(fmt) = config.get_str("log.file_format") {
            if fmt.eq_ignore_ascii_case("json") {
                base.json_format = true;
            }
        }

        if let Some(rotate) = config.get_str("log.rotate_when") {
            if !rotate.is_empty() {
                base.rotate_when = rotate.to_string();
            }
        }

        if let Some(v) = config.get_u64("log.max_bytes") {
            if v > 0 {
                base.max_bytes = v;
            }
        }

        if let Some(v) = config.get_bool("log.console_enabled") {
            base.console_enabled = v;
        }

        if let Some(v) = config.get_bool("log.file_enabled") {
            base.file_enabled = v;
        }

        if let Some(v) = config.get_bool("log.color_blocks") {
            base.color_blocks = v;
        }

        base
    }

    /// Creates a log configuration from environment variables.
    /// 
    /// This method reads logging configuration from environment variables:
    /// - Ri_LOG_LEVEL: Log level (DEBUG, INFO, WARN, ERROR)
    /// - Ri_LOG_CONSOLE_ENABLED: Whether console logging is enabled (true/false)
    /// - Ri_LOG_FILE_ENABLED: Whether file logging is enabled (true/false)
    /// - Ri_LOG_SAMPLING_DEFAULT: Default sampling rate (0.0-1.0)
    /// - Ri_LOG_FILE_NAME: Name of the log file
    /// - Ri_LOG_FILE_FORMAT: Log format ("json" for JSON format)
    /// - Ri_LOG_ROTATE_WHEN: When to rotate logs
    /// - Ri_LOG_MAX_BYTES: Maximum file size before rotation
    /// 
    /// # Returns
    /// 
    /// A `RiLogConfig` instance with configuration from environment variables
    pub fn from_env() -> Self {
        let mut base = RiLogConfig::default();

        if let Some(level) = RiLogLevel::from_env() {
            base.level = level;
        }

        if let Ok(v) = std::env::var("Ri_LOG_SAMPLING_DEFAULT") {
            if let Ok(rate) = v.parse::<f32>() {
                base.sampling_default = rate.clamp(0.0, 1.0);
            }
        }

        if let Ok(file_name) = std::env::var("Ri_LOG_FILE_NAME") {
            if !file_name.is_empty() {
                base.file_name = file_name;
            }
        }

        if let Ok(fmt) = std::env::var("Ri_LOG_FILE_FORMAT") {
            if fmt.eq_ignore_ascii_case("json") {
                base.json_format = true;
            }
        }

        if let Ok(rotate) = std::env::var("Ri_LOG_ROTATE_WHEN") {
            if !rotate.is_empty() {
                base.rotate_when = rotate;
            }
        }

        if let Ok(v) = std::env::var("Ri_LOG_MAX_BYTES") {
            if let Ok(bytes) = v.parse::<u64>() {
                if bytes > 0 {
                    base.max_bytes = bytes;
                }
            }
        }

        if let Ok(v) = std::env::var("Ri_LOG_CONSOLE_ENABLED") {
            if v.eq_ignore_ascii_case("true") || v == "1" {
                base.console_enabled = true;
            } else if v.eq_ignore_ascii_case("false") || v == "0" {
                base.console_enabled = false;
            }
        }

        if let Ok(v) = std::env::var("Ri_LOG_FILE_ENABLED") {
            if v.eq_ignore_ascii_case("true") || v == "1" {
                base.file_enabled = true;
            } else if v.eq_ignore_ascii_case("false") || v == "0" {
                base.file_enabled = false;
            }
        }

        if let Ok(v) = std::env::var("Ri_LOG_COLOR_BLOCKS") {
            if v.eq_ignore_ascii_case("true") || v == "1" {
                base.color_blocks = true;
            } else if v.eq_ignore_ascii_case("false") || v == "0" {
                base.color_blocks = false;
            }
        }

        base
    }
}

/// Default implementation for RiLogConfig
impl Default for RiLogConfig {
    fn default() -> Self {
        RiLogConfig {
            level: RiLogLevel::Info,
            console_enabled: true,
            file_enabled: true,
            sampling_default: 1.0,
            file_name: "dms.log".to_string(),
            json_format: false,
            rotate_when: "size".to_string(),
            max_bytes: 10 * 1024 * 1024,
            color_blocks: true,
        }
    }
}

/// Log entry for caching
struct LogEntry {
    level: RiLogLevel,
    target: String,
    message: String,
    timestamp: String,
    context: serde_json::Map<String, serde_json::Value>,
}

/// Internal logger implementation.
/// 
/// This struct contains the internal implementation of the logging system, including
/// log level checking, sampling, log message formatting, and caching.
#[derive(Clone)]
struct LoggerImpl {
    /// Minimum log level to be logged
    level: RiLogLevel,
    /// File system instance for writing log files
    #[allow(dead_code)]
    fs: RiFileSystem,
    /// Default sampling rate
    sampling_default: f32,
    /// Whether console logging is enabled
    #[allow(dead_code)]
    console_enabled: bool,
    /// Whether file logging is enabled
    #[allow(dead_code)]
    file_enabled: bool,
    /// Name of the log file
    #[allow(dead_code)]
    file_name: String,
    /// Whether to use JSON format for logs
    #[allow(dead_code)]
    json_format: bool,
    /// When to rotate logs (currently only "size" or "none" are supported)
    #[allow(dead_code)]
    rotate_when: String,
    /// Maximum file size in bytes before rotation (used when rotate_when == "size")
    #[allow(dead_code)]
    max_bytes: u64,
    /// Whether to use color blocks in log output
    #[allow(dead_code)]
    color_blocks: bool,
    /// Log cache for batch writing
    log_cache: Arc<(Mutex<VecDeque<LogEntry>>, Condvar)>,
    /// Cache size limit
    cache_size_limit: usize,
    /// Flush interval in milliseconds
    #[allow(dead_code)]
    flush_interval_ms: u64,
    /// Shutdown flag
    #[allow(dead_code)]
    shutdown_flag: Arc<Mutex<bool>>,
}

impl LoggerImpl {
    /// Creates a new internal logger implementation.
    /// 
    /// # Parameters
    /// 
    /// - `config`: The `RiLogConfig` instance to use for configuration
    /// - `fs`: The `RiFileSystem` instance to use for writing log files
    /// 
    /// # Returns
    /// 
    /// A new `LoggerImpl` instance
    fn new(config: &RiLogConfig, fs: RiFileSystem) -> Self {
        let log_cache = Arc::new((Mutex::new(VecDeque::new()), Condvar::new()));
        let shutdown_flag = Arc::new(Mutex::new(false));
        let cache_size_limit = 1000;
        let flush_interval_ms = 500;
        
        // Create a copy of the necessary fields for the background thread
        let bg_log_cache = Arc::clone(&log_cache);
        let bg_fs = fs.clone();
        let bg_file_name = config.file_name.clone();
        let bg_json_format = config.json_format;
        let bg_rotate_when = config.rotate_when.clone();
        let bg_max_bytes = config.max_bytes;
        let bg_console_enabled = config.console_enabled;
        let bg_color_blocks = config.color_blocks;
        let bg_shutdown_flag = Arc::clone(&shutdown_flag);
        
        // Start background flush thread
        thread::spawn(move || {
            let mut last_flush = SystemTime::now();
            
            loop {
                // Check if we should shutdown
                let shutdown_flag = bg_shutdown_flag.lock().expect("Log shutdown flag lock poisoned");
                if *shutdown_flag {
                    // Flush remaining logs before shutting down
                    Self::flush_cache(
                        &bg_log_cache,
                        &bg_fs,
                        &bg_file_name,
                        bg_json_format,
                        &bg_rotate_when,
                        bg_max_bytes,
                        bg_console_enabled,
                        bg_color_blocks
                    ).unwrap_or(());
                    break;
                }
                drop(shutdown_flag);
                
                // Check if we need to flush based on time or cache size
                let now = SystemTime::now();
                let time_since_last_flush = now.duration_since(last_flush).unwrap_or(Duration::from_millis(0));
                
                let cache_len = bg_log_cache.0.lock().expect("Log cache lock poisoned").len();
                
                if time_since_last_flush >= Duration::from_millis(flush_interval_ms) || cache_len >= cache_size_limit {
                    Self::flush_cache(
                        &bg_log_cache,
                        &bg_fs,
                        &bg_file_name,
                        bg_json_format,
                        &bg_rotate_when,
                        bg_max_bytes,
                        bg_console_enabled,
                        bg_color_blocks
                    ).unwrap_or(());
                    last_flush = now;
                }
                
                // Wait for a short time or until signaled
                let (lock, cvar) = &*bg_log_cache;
                let _ = cvar.wait_timeout(lock.lock().unwrap(), Duration::from_millis(100)).unwrap();
            }
        });
        
        LoggerImpl {
            level: config.level,
            fs,
            sampling_default: config.sampling_default,
            console_enabled: config.console_enabled,
            file_enabled: config.file_enabled,
            file_name: config.file_name.clone(),
            json_format: config.json_format,
            rotate_when: config.rotate_when.clone(),
            max_bytes: config.max_bytes,
            color_blocks: config.color_blocks,
            log_cache,
            cache_size_limit,
            flush_interval_ms,
            shutdown_flag,
        }
    }
    
    /// Flushes the log cache to disk and console
    /// 
    /// # Parameters
    /// 
    /// - `log_cache`: The log cache to flush
    /// - `fs`: The file system instance to use for writing log files
    /// - `file_name`: The name of the log file
    /// - `json_format`: Whether to use JSON format for logs
    /// - `rotate_when`: When to rotate logs
    /// - `max_bytes`: Maximum file size before rotation
    /// - `console_enabled`: Whether console logging is enabled
    /// - `color_blocks`: Whether to use color blocks in log output
    /// 
    /// # Returns
    /// 
    /// A `RiResult` indicating success or failure
    fn flush_cache(
        log_cache: &Arc<(Mutex<VecDeque<LogEntry>>, Condvar)>,
        fs: &RiFileSystem,
        file_name: &str,
        json_format: bool,
        rotate_when: &str,
        max_bytes: u64,
        console_enabled: bool,
        color_blocks: bool
    ) -> RiResult<()> {
        let (lock, _cvar) = &**log_cache;
        let mut cache = lock.lock().unwrap();
        
        if cache.is_empty() {
            return Ok(());
        }
        
        // Collect all logs to flush
        let logs_to_flush: Vec<LogEntry> = cache.drain(..).collect();
        drop(cache);
        
        // Process logs in batch
        let mut file_logs = Vec::with_capacity(4);
        let mut console_logs = Vec::with_capacity(4);
        
        for log_entry in logs_to_flush {
            // Format log entry
            let line = if json_format {
                // Ensure all required fields are present in JSON format
                let mut log_obj = log_entry.context.clone();
                
                // Add any missing standard fields
                if !log_obj.contains_key("level") {
                    log_obj.insert("level".to_string(), serde_json::Value::String(log_entry.level.as_str().to_string()));
                }
                if !log_obj.contains_key("target") {
                    log_obj.insert("target".to_string(), serde_json::Value::String(log_entry.target.clone()));
                }
                if !log_obj.contains_key("message") {
                    log_obj.insert("message".to_string(), serde_json::Value::String(log_entry.message.clone()));
                }
                if !log_obj.contains_key("timestamp") {
                    log_obj.insert("timestamp".to_string(), serde_json::Value::String(log_entry.timestamp.clone()));
                }
                
                serde_json::to_string(&log_obj)?
            } else {
                // Extract context fields for text format
                let ctx_kv: Vec<(String, String)> = log_entry.context.iter()
                    .filter(|(k, _)| *k != "timestamp" && *k != "level" && *k != "target" && *k != "message" && *k != "trace_id" && *k != "span_id")
                    .map(|(k, v)| (k.clone(), v.to_string()))
                    .collect();
                
                // Extract trace and span IDs if present
                let trace_info = match (log_entry.context.get("trace_id"), log_entry.context.get("span_id")) {
                    (Some(trace), Some(span)) => format!(" trace_id={trace} span_id={span}"),
                    (Some(trace), None) => format!(" trace_id={trace}"),
                    (None, Some(span)) => format!(" span_id={span}"),
                    (None, None) => String::new(),
                };
                
                // Extract event name from context or use target as fallback
                let event = log_entry.context.get("event")
                    .and_then(|v| v.as_str())
                    .unwrap_or(&log_entry.target);
                
                // Format context fields for display
                let ctx_display = if ctx_kv.is_empty() {
                    String::new()
                } else {
                    let parts: Vec<String> = ctx_kv
                        .iter()
                        .map(|(k, v)| format!("{}={}", k, v))
                        .collect();
                    format!(" | {}", parts.join(", "))
                };
                
                // Format trace info for display
                let trace_display = if trace_info.is_empty() {
                    String::new()
                } else {
                    format!(" | {}", trace_info.trim())
                };
                
                // New log format with optional color block and | separators
                let color_block = if color_blocks {
                    log_entry.level.color_block()
                } else {
                    ""
                };
                let color_sep = if color_blocks { " | " } else { "" };
                format!(
                    "{}{}{} | {:5} | {} | event={}{} | {}{}",
                    color_block,
                    color_sep,
                    log_entry.timestamp,
                    log_entry.level.as_str(),
                    log_entry.target,
                    event,
                    trace_display,
                    log_entry.message,
                    ctx_display,
                )
            };
            
            // Separate console and file logs
            if console_enabled {
                console_logs.push(line.clone());
            }
            
            if !line.is_empty() {
                file_logs.push(line);
            }
        }
        
        // Write to console in batch
        if !console_logs.is_empty() {
            for line in console_logs {
                log::info!("{line}");
            }
        }
        
        // Write to file in batch
        if !file_logs.is_empty() {
            let log_file = fs.logs_dir().join(file_name);
            
            // Simple size-based rotation if enabled
            if rotate_when.eq_ignore_ascii_case("size") && max_bytes > 0 {
                if let Ok(meta) = stdfs::metadata(&log_file) {
                    if meta.len() >= max_bytes {
                        if let Some(parent) = log_file.parent() {
                            let base = log_file.file_name().and_then(|s| s.to_str()).unwrap_or("dms.log");
                            let ts = SystemTime::now()
                                .duration_since(UNIX_EPOCH)
                                .map_err(|e| crate::core::RiError::Other(format!("timestamp error: {e}")))?;
                            let rotated = parent.join(format!("{}.{}", base, ts.as_millis()));
                            let _ = stdfs::rename(&log_file, &rotated);
                        }
                    }
                }
            }
            
            // Batch write to file
            let content = file_logs.join("\n") + "\n";
            fs.append_text(&log_file, &content)?;
        }
        
        Ok(())
    }

    /// Determines if a message with the given level should be logged.
    /// 
    /// # Parameters
    /// 
    /// - `level`: The log level of the message
    /// 
    /// # Returns
    /// 
    /// `true` if the message should be logged, `false` otherwise
    fn should_log(&self, level: RiLogLevel) -> bool {
        (level as u8) >= (self.level as u8)
    }

    /// Determines if an event should be logged based on sampling.
    /// 
    /// # Parameters
    /// 
    /// - `_event`: The event name (currently unused, reserved for future per-event sampling)
    /// 
    /// # Returns
    /// 
    /// `true` if the event should be logged, `false` otherwise
    fn should_log_event(&self, event: &str) -> bool {
        // Advanced event-based sampling with per-event configuration support
        
        // First check if we have specific sampling rules for this event
        if let Some(event_sampling_rate) = self.get_event_sampling_rate(event) {
            if event_sampling_rate >= 1.0 {
                return true;
            } else if event_sampling_rate <= 0.0 {
                return false;
            } else {
                let r = rand::random::<f32>();
                return r < event_sampling_rate;
            }
        }
        
        // Fall back to default sampling rate
        if self.sampling_default >= 1.0 {
            true
        } else if self.sampling_default <= 0.0 {
            false
        } else {
            let r = rand::random::<f32>();
            r < self.sampling_default
        }
    }
    
    /// Get the sampling rate for a specific event type
    /// 
    /// # Parameters
    /// 
    /// - `event`: The event name to get sampling rate for
    /// 
    /// # Returns
    /// 
    /// Optional sampling rate (0.0 to 1.0) if specific rate is configured
    fn get_event_sampling_rate(&self, event: &str) -> Option<f32> {
        // In a production environment, this would:
        // 1. Load per-event sampling configuration from config files
        // 2. Support dynamic configuration updates
        // 3. Handle event patterns and categories
        // 4. Support A/B testing for different sampling rates
        
        // For now, we support a few common event types with different sampling rates
        match event {
            "database_query" => Some(0.1),      // Sample 10% of database queries
            "api_request" => Some(0.5),        // Sample 50% of API requests
            "cache_hit" => Some(0.05),         // Sample 5% of cache hits
            "cache_miss" => Some(1.0),         // Log all cache misses
            "error" => Some(1.0),             // Log all errors
            "warning" => Some(0.8),           // Log 80% of warnings
            _ => None,                         // Use default for unknown events
        }
    }

    /// Returns the current timestamp in ISO 8601 format.
    /// 
    /// # Returns
    /// 
    /// A string representing the current timestamp in ISO 8601 format (e.g., "1630000000.123Z")
    fn now_timestamp() -> String {
        match SystemTime::now().duration_since(UNIX_EPOCH) {
            Ok(dur) => {
                let secs = dur.as_secs();
                let millis = dur.subsec_millis();
                format!("{secs}.{millis:03}Z")
            }
            Err(_) => "0.000Z".to_string(),
        }
    }

    /// Sanitizes a log message to prevent log injection attacks.
    ///
    /// # Security
    ///
    /// This function prevents:
    /// 1. CRLF injection (carriage return / line feed)
    /// 2. ANSI escape sequences
    /// 3. Null byte injection
    /// 4. Control characters
    /// 5. Excessive length
    ///
    /// # Parameters
    /// 
    /// - `message`: The message to sanitize
    /// 
    /// # Returns
    /// 
    /// A sanitized string safe for logging
    fn sanitize_log_message(message: &str) -> String {
        let mut result = String::with_capacity(message.len().min(4096));
        
        for c in message.chars() {
            match c {
                // Allow printable ASCII characters
                ' '..='~' => {
                    // Escape backslash to prevent escape sequence injection
                    if c == '\\' {
                        result.push_str("\\\\");
                    } else {
                        result.push(c);
                    }
                }
                // Allow Unicode letters and numbers
                c if c.is_alphanumeric() => {
                    result.push(c);
                }
                // Handle newlines - convert to safe representation
                '\n' => result.push_str("\\n"),
                '\r' => result.push_str("\\r"),
                '\t' => result.push_str("\\t"),
                // Skip control characters, ANSI sequences, null bytes, etc.
                _ => continue,
            }
        }
        
        // Limit length to prevent log flooding
        if result.len() > 4096 {
            result.truncate(4096);
            result.push_str("...[truncated]");
        }
        
        result
    }

    /// Logs a message with the given level, target, and message.
    /// 
    /// This method handles the complete logging process, including:
    /// 1. Checking if the message should be logged based on level
    /// 2. Sampling the message if applicable
    /// 3. Formatting the message (text or JSON)
    /// 4. Adding contextual information and distributed tracing fields
    /// 5. Adding the log entry to the cache for batch processing
    /// 
    /// # Parameters
    /// 
    /// - `level`: The log level of the message
    /// - `target`: The target of the log message (usually a module or component name)
    /// - `message`: The message to log (must implement `Debug`)
    /// 
    /// # Returns
    /// 
    /// A `RiResult` indicating success or failure
    fn log_message<T: Debug>(&self, level: RiLogLevel, target: &str, message: T) -> RiResult<()> {
        if !self.should_log(level) {
            return Ok(());
        }

        let event = target; // simple default; can be extended to accept explicit event names.
        if !self.should_log_event(event) {
            return Ok(());
        }

        let ts = Self::now_timestamp();
        let message_str = format!("{message:?}");
        
        // Security: Sanitize message to prevent log injection
        let sanitized_message = Self::sanitize_log_message(&message_str);
        let sanitized_target = Self::sanitize_log_message(target);

        let ctx_kv = RiLogContext::get_all();

        // Create log entry with structured data
        let mut log_entry_context = serde_json::Map::new();
        log_entry_context.insert("timestamp".to_string(), json!(ts));
        log_entry_context.insert("level".to_string(), json!(level.as_str()));
        log_entry_context.insert("target".to_string(), json!(sanitized_target));
        log_entry_context.insert("event".to_string(), json!(sanitized_target));
        log_entry_context.insert("message".to_string(), json!(sanitized_message));
        
        // Add distributed tracing fields if present
        if let Some(trace_id) = RiLogContext::get_trace_id() {
            log_entry_context.insert("trace_id".to_string(), json!(Self::sanitize_log_message(&trace_id)));
        }
        if let Some(span_id) = RiLogContext::get_span_id() {
            log_entry_context.insert("span_id".to_string(), json!(Self::sanitize_log_message(&span_id)));
        }
        if let Some(parent_span_id) = RiLogContext::get_parent_span_id() {
            log_entry_context.insert("parent_span_id".to_string(), json!(Self::sanitize_log_message(&parent_span_id)));
        }
        
        // Add context fields
        if !ctx_kv.is_empty() {
            for (k, v) in ctx_kv.iter() {
                log_entry_context.insert(
                    Self::sanitize_log_message(k),
                    json!(Self::sanitize_log_message(v))
                );
            }
        }

        // Create log entry for caching
        let log_entry = LogEntry {
            level,
            target: sanitized_target,
            message: sanitized_message,
            timestamp: ts,
            context: log_entry_context,
        };

        // Add log entry to cache
        let (lock, cvar) = &*self.log_cache;
        let mut cache = lock.lock().unwrap();
        cache.push_back(log_entry);
        
        // Signal the background thread if cache is full
        if cache.len() >= self.cache_size_limit {
            cvar.notify_one();
        }
        
        Ok(())
    }
}

/// Public-facing logger class.
/// 
/// This struct provides the public API for logging in Ri, wrapping the internal `LoggerImpl`.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
#[derive(Clone)]
pub struct RiLogger {
    /// Internal logger implementation
    inner: LoggerImpl,
}

impl RiLogger {
    /// Creates a new logger instance.
    /// 
    /// # Parameters
    /// 
    /// - `config`: The `RiLogConfig` instance to use for configuration
    /// - `fs`: The `RiFileSystem` instance to use for writing log files
    /// 
    /// # Returns
    /// 
    /// A new `RiLogger` instance
    pub fn new(config: &RiLogConfig, fs: RiFileSystem) -> Self {
        let inner = LoggerImpl::new(config, fs);
        RiLogger { inner }
    }

    /// Logs a debug message.
    /// 
    /// # Parameters
    /// 
    /// - `target`: The target of the log message (usually a module or component name)
    /// - `message`: The message to log (must implement `Debug`)
    /// 
    /// # Returns
    /// 
    /// A `RiResult` indicating success or failure
    pub fn debug<T: Debug>(&self, target: &str, message: T) -> RiResult<()> {
        self.inner.log_message(RiLogLevel::Debug, target, message)
    }

    /// Logs an info message.
    /// 
    /// # Parameters
    /// 
    /// - `target`: The target of the log message (usually a module or component name)
    /// - `message`: The message to log (must implement `Debug`)
    /// 
    /// # Returns
    /// 
    /// A `RiResult` indicating success or failure
    pub fn info<T: Debug>(&self, target: &str, message: T) -> RiResult<()> {
        self.inner.log_message(RiLogLevel::Info, target, message)
    }

    /// Logs a warning message.
    /// 
    /// # Parameters
    /// 
    /// - `target`: The target of the log message (usually a module or component name)
    /// - `message`: The message to log (must implement `Debug`)
    /// 
    /// # Returns
    /// 
    /// A `RiResult` indicating success or failure
    pub fn warn<T: Debug>(&self, target: &str, message: T) -> RiResult<()> {
        self.inner.log_message(RiLogLevel::Warn, target, message)
    }

    /// Logs an error message.
    /// 
    /// # Parameters
    /// 
    /// - `target`: The target of the log message (usually a module or component name)
    /// - `message`: The message to log (must implement `Debug`)
    /// 
    /// # Returns
    /// 
    /// A `RiResult` indicating success or failure
    pub fn error<T: Debug>(&self, target: &str, message: T) -> RiResult<()> {
        self.inner.log_message(RiLogLevel::Error, target, message)
    }
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiLogger {
    #[new]
    fn py_new(config: RiLogConfig, fs: RiFileSystem) -> Self {
        Self::new(&config, fs)
    }

    #[pyo3(name = "debug")]
    fn py_debug(&self, target: &str, message: &str) -> pyo3::PyResult<()> {
        self.inner
            .log_message(RiLogLevel::Debug, target, message)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
    }

    #[pyo3(name = "info")]
    fn py_info(&self, target: &str, message: &str) -> pyo3::PyResult<()> {
        self.inner
            .log_message(RiLogLevel::Info, target, message)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
    }

    #[pyo3(name = "warn")]
    fn py_warn(&self, target: &str, message: &str) -> pyo3::PyResult<()> {
        self.inner
            .log_message(RiLogLevel::Warn, target, message)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
    }

    #[pyo3(name = "error")]
    fn py_error(&self, target: &str, message: &str) -> pyo3::PyResult<()> {
        self.inner
            .log_message(RiLogLevel::Error, target, message)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
    }
}