nonblocking-logger 0.3.0

A high-performance library with format string support
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
use crate::enums::log_level::LogLevel;
use std::collections::HashMap;
use std::io::{self, Write};
use std::sync::RwLock;

/// A simple, flexible logger that supports multiple targets and custom formats
pub struct Logger {
    level: LogLevel,
    time_format: String,
    format_strings: HashMap<LogLevel, String>,
    targets: Vec<RwLock<Box<dyn Write + Send + Sync>>>,
}

impl Logger {
    /// Create a new logger with default settings
    pub fn new() -> Self {
        Self {
            level: LogLevel::Info,
            time_format: "%Y-%m-%d %H:%M:%S".to_string(),
            format_strings: Self::default_format_strings(),
            targets: vec![RwLock::new(Box::new(io::stdout()))],
        }
    }

    /// Create a logger with a specific log level
    pub fn with_level(level: LogLevel) -> Self {
        Self {
            level,
            time_format: "%Y-%m-%d %H:%M:%S".to_string(),
            format_strings: Self::default_format_strings(),
            targets: vec![RwLock::new(Box::new(io::stdout()))],
        }
    }

    /// Create a logger configured from environment variables
    ///
    /// This method checks for log level configuration in the following order:
    /// 1. RUST_LOG environment variable (Rust convention)
    /// 2. LOG_LEVEL environment variable (fallback)
    ///
    /// If neither is found or both are invalid, defaults to Info level.
    pub fn from_env() -> Self {
        use crate::utils::log_util::parse_log_level_from_env;
        let level = parse_log_level_from_env();
        Self::with_level(level)
    }

    /// Set the time format using chrono format string
    ///
    /// Common formats:
    /// - `%Y-%m-%d %H:%M:%S` - "2025-09-14 16:57:00" (default)
    /// - `%H:%M:%S` - "16:57:00"
    /// - `%Y-%m-%d %H:%M:%S%.3f` - "2025-09-14 16:57:00.123"
    /// - `%Y-%m-%d` - "2025-09-14"
    pub fn time_format(mut self, format: &str) -> Self {
        self.time_format = format.to_string();
        self
    }

    /// Disable time prefix
    ///
    /// This sets the time format to empty string, effectively removing timestamps.
    pub fn no_time_prefix(mut self) -> Self {
        self.time_format = String::new();
        self
    }

    /// Set the same custom format string for **all** log levels
    ///
    /// This overwrites the default per-level formats with a single format template.
    /// Placeholders:
    /// - `{time}`   - formatted timestamp (see `time_format`)
    /// - `{level}`  - log level (ERROR, WARN, INFO, DEBUG, TRACE)
    /// - `{message}` - the log message
    pub fn format(mut self, format: String) -> Self {
        let levels = [
            LogLevel::Error,
            LogLevel::Warning,
            LogLevel::Info,
            LogLevel::Debug,
            LogLevel::Trace,
        ];

        for level in levels {
            self.format_strings.insert(level, format.clone());
        }

        self
    }

    /// Set custom format string for a specific log level
    pub fn format_for_level(mut self, level: LogLevel, format: String) -> Self {
        self.format_strings.insert(level, format);
        self
    }

    /// Set a target to write logs to (stdout) - replaces all existing targets
    pub fn stdout(mut self) -> Self {
        self.targets = vec![RwLock::new(Box::new(io::stdout()))];
        self
    }

    /// Set a target to write logs to (stderr) - replaces all existing targets
    pub fn stderr(mut self) -> Self {
        self.targets = vec![RwLock::new(Box::new(io::stderr()))];
        self
    }

    /// Add a file as a target - replaces all existing targets
    pub fn file(mut self, path: &str) -> io::Result<Self> {
        let file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)?;
        self.targets = vec![RwLock::new(Box::new(file))];
        Ok(self)
    }

    /// Set a custom Write target - replaces all existing targets
    ///
    /// This allows you to set any type that implements `Write + Send + Sync` as the only logging target.
    /// Useful for custom writers, network streams, or any other Write implementor.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nonblocking_logger::Logger;
    /// use std::io::Write;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let mut buffer = Vec::new();
    ///     let logger = Logger::new().custom(buffer);
    ///     
    ///     logger.info("This will be written to the custom target only")?;
    ///     Ok(())
    /// }
    /// ```
    pub fn custom<W>(mut self, target: W) -> Self 
    where 
        W: Write + Send + Sync + 'static 
    {
        self.targets = vec![RwLock::new(Box::new(target))];
        self
    }

    /// Add a stdout target to existing targets
    pub fn add_stdout(mut self) -> Self {
        self.targets.push(RwLock::new(Box::new(io::stdout())));
        self
    }

    /// Add a stderr target to existing targets
    pub fn add_stderr(mut self) -> Self {
        self.targets.push(RwLock::new(Box::new(io::stderr())));
        self
    }

    /// Add a file target to existing targets
    pub fn add_file(mut self, path: &str) -> io::Result<Self> {
        let file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)?;
        self.targets.push(RwLock::new(Box::new(file)));
        Ok(self)
    }

    /// Add a custom Write target to existing targets
    ///
    /// This allows you to add any type that implements `Write + Send + Sync` as a logging target.
    /// Useful for custom writers, network streams, or any other Write implementor.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nonblocking_logger::Logger;
    /// use std::io::Write;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let mut buffer = Vec::new();
    ///     let logger = Logger::new().add_target(buffer);
    ///     
    ///     logger.info("This will be written to the custom target")?;
    ///     Ok(())
    /// }
    /// ```
    pub fn add_target<W>(mut self, target: W) -> Self 
    where 
        W: Write + Send + Sync + 'static 
    {
        self.targets.push(RwLock::new(Box::new(target)));
        self
    }


    /// Log a message (always outputs, no level filtering)
    pub fn log(&self, message: &str) -> io::Result<()> {
        let formatted = self.format_message_simple(message);

        for target in &self.targets {
            let mut target = target.write().unwrap();
            writeln!(target, "{}", formatted)?;
            target.flush()?;
        }

        Ok(())
    }

    /// Log a message with lazy evaluation (always outputs, no level filtering)
    ///
    /// This is more efficient when the message requires expensive computation, as the closure
    /// will only be executed if the log level allows the message to be output.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nonblocking_logger::Logger;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let logger = Logger::new();
    ///     
    ///     // This expensive computation will always run and output
    ///     logger.log_lazy(|| {
    ///         format!("Expensive computation result: {}", "some_expensive_result")
    ///     })?;
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub fn log_lazy<F>(&self, message_fn: F) -> io::Result<()>
    where
        F: FnOnce() -> String,
    {
        let message = message_fn();
        self.log(&message)
    }


    /// Log a message with lazy evaluation and specific level (with filtering)
    pub(crate) fn log_lazy_with_level<F>(&self, level: LogLevel, message_fn: F) -> io::Result<()>
    where
        F: FnOnce() -> String,
    {
        if level < self.level {
            return Ok(());
        }

        let message = message_fn();
        self.log_with_level(level, &message)
    }

    /// Log a message with a specific level (with filtering)
    pub(crate) fn log_with_level(&self, level: LogLevel, message: &str) -> io::Result<()> {
        if level < self.level {
            return Ok(());
        }

        let formatted = self.format_message(level, message);

        for target in &self.targets {
            let mut target = target.write().unwrap();
            writeln!(target, "{}", formatted)?;
            target.flush()?;
        }

        Ok(())
    }

    /// Convenience methods for each log level
    pub fn error(&self, message: &str) -> io::Result<()> {
        self.log_with_level(LogLevel::Error, message)
    }

    pub fn warning(&self, message: &str) -> io::Result<()> {
        self.log_with_level(LogLevel::Warning, message)
    }

    pub fn info(&self, message: &str) -> io::Result<()> {
        self.log_with_level(LogLevel::Info, message)
    }

    pub fn debug(&self, message: &str) -> io::Result<()> {
        self.log_with_level(LogLevel::Debug, message)
    }

    pub fn trace(&self, message: &str) -> io::Result<()> {
        self.log_with_level(LogLevel::Trace, message)
    }

    /// Convenience methods for each log level with lazy evaluation
    ///
    /// These methods only execute the closure if the log level is sufficient,
    /// making them more efficient for expensive message computations.
    pub fn error_lazy<F>(&self, message_fn: F) -> io::Result<()>
    where
        F: FnOnce() -> String,
    {
        self.log_lazy_with_level(LogLevel::Error, message_fn)
    }

    pub fn warning_lazy<F>(&self, message_fn: F) -> io::Result<()>
    where
        F: FnOnce() -> String,
    {
        self.log_lazy_with_level(LogLevel::Warning, message_fn)
    }

    pub fn info_lazy<F>(&self, message_fn: F) -> io::Result<()>
    where
        F: FnOnce() -> String,
    {
        self.log_lazy_with_level(LogLevel::Info, message_fn)
    }

    pub fn debug_lazy<F>(&self, message_fn: F) -> io::Result<()>
    where
        F: FnOnce() -> String,
    {
        self.log_lazy_with_level(LogLevel::Debug, message_fn)
    }

    pub fn trace_lazy<F>(&self, message_fn: F) -> io::Result<()>
    where
        F: FnOnce() -> String,
    {
        self.log_lazy_with_level(LogLevel::Trace, message_fn)
    }

    /// Set the log level
    pub fn set_level(&mut self, level: LogLevel) {
        self.level = level;
    }

    /// Set the time format using chrono format string
    ///
    /// Common formats:
    /// - `%Y-%m-%d %H:%M:%S` - "2025-09-14 16:57:00" (default)
    /// - `%H:%M:%S` - "16:57:00"
    /// - `%Y-%m-%d %H:%M:%S%.3f` - "2025-09-14 16:57:00.123"
    /// - `%Y-%m-%d` - "2025-09-14"
    pub fn set_time_format(&mut self, format: &str) {
        self.time_format = format.to_string();
    }

    /// Disable time prefix
    ///
    /// This sets the time format to empty string, effectively removing timestamps.
    pub fn disable_time_prefix(&mut self) {
        self.time_format = String::new();
    }

    /// Set custom format string for a specific log level
    pub fn set_format_for_level(&mut self, level: LogLevel, format: &str) {
        self.format_strings.insert(level, format.to_string());
    }

    /// Get the current log level
    pub fn level(&self) -> LogLevel {
        self.level
    }

    /// Get the current log level (alias for level for compatibility)
    pub fn get_level(&self) -> LogLevel {
        self.level
    }

    /// Clear all targets
    pub fn clear_targets(mut self) -> Self {
        self.targets.clear();
        self
    }

    fn default_format_strings() -> HashMap<LogLevel, String> {
        let mut formats = HashMap::new();
        formats.insert(LogLevel::Error, "{time} [{level}] {message}".to_string());
        formats.insert(LogLevel::Warning, "{time} [{level}] {message}".to_string());
        formats.insert(LogLevel::Info, "{time} [{level}] {message}".to_string());
        formats.insert(LogLevel::Debug, "{time} [{level}] {message}".to_string());
        formats.insert(LogLevel::Trace, "{time} [{level}] {message}".to_string());
        formats
    }

    fn format_message(&self, level: LogLevel, message: &str) -> String {
        let format_string = self
            .format_strings
            .get(&level)
            .unwrap_or(&self.format_strings[&LogLevel::Info])
            .clone();

        let time_str = if self.time_format.is_empty() {
            String::new()
        } else {
            use simple_datetime_rs::{DateTime, Format};
            DateTime::now()
                .format(&self.time_format)
                .unwrap_or_default()
        };

        format_string
            .replace("{time}", &time_str)
            .replace("{level}", &level.to_string())
            .replace("{message}", message)
    }

    fn format_message_simple(&self, message: &str) -> String {
        if self.time_format.is_empty() {
            message.to_string()
        } else {
            use simple_datetime_rs::{DateTime, Format};
            let time_str = DateTime::now()
                .format(&self.time_format)
                .unwrap_or_default();
            format!("{} {}", time_str, message)
        }
    }
}

impl Default for Logger {
    fn default() -> Self {
        Self::new()
    }
}

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

    /// Create a test logger that writes to a Cursor<Vec<u8>> instead of stdout
    /// This allows us to verify the actual log output in tests
    fn create_test_logger() -> (Logger, std::io::Cursor<Vec<u8>>) {
        let cursor = Cursor::new(Vec::<u8>::new());
        let cursor_clone = Cursor::new(Vec::<u8>::new());

        let logger = Logger {
            level: LogLevel::Info,
            time_format: String::new(), // No time prefix for cleaner tests
            format_strings: Logger::default_format_strings(),
            targets: vec![RwLock::new(Box::new(cursor_clone))],
        };

        (logger, cursor)
    }

    /// Create a test logger with a specific log level
    fn create_test_logger_with_level(level: LogLevel) -> (Logger, std::io::Cursor<Vec<u8>>) {
        let (mut logger, cursor) = create_test_logger();
        logger.level = level;
        (logger, cursor)
    }

    /// Create a test logger that allows us to capture and verify the actual log output
    /// This is useful for testing the actual formatted output
    fn create_capturable_test_logger() -> (Logger, std::sync::Arc<std::sync::Mutex<Vec<u8>>>) {
        use std::io::Write;

        let buffer = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
        let buffer_clone = buffer.clone();

        struct CapturingWriter {
            buffer: std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
        }

        impl Write for CapturingWriter {
            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
                self.buffer.lock().unwrap().extend_from_slice(buf);
                Ok(buf.len())
            }

            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        let logger = Logger {
            level: LogLevel::Info,
            time_format: String::new(), // No time prefix for cleaner tests
            format_strings: Logger::default_format_strings(),
            targets: vec![RwLock::new(Box::new(CapturingWriter {
                buffer: buffer_clone,
            }))],
        };

        (logger, buffer)
    }

    #[test]
    fn test_simple_logging() -> io::Result<()> {
        let (logger, _cursor) = create_test_logger();

        assert_eq!(logger.level(), LogLevel::Info);

        logger.info("Hello, world!")?;
        logger.warning("This is a warning")?;
        logger.error("This is an error")?;

        assert_eq!(logger.level(), LogLevel::Info);

        Ok(())
    }

    #[test]
    fn test_time_format() -> io::Result<()> {
        let (mut logger, _cursor) = create_test_logger();
        logger.time_format = "%Y-%m-%d %H:%M:%S".to_string();

        assert_eq!(logger.level(), LogLevel::Info);

        logger.info("Test message")?;

        logger.warning("Another test message")?;

        Ok(())
    }

    #[test]
    fn test_custom_format() -> io::Result<()> {
        let (mut logger, _cursor) = create_test_logger();
        logger
            .format_strings
            .insert(LogLevel::Error, "ERROR: {message}".to_string());

        assert_eq!(logger.level(), LogLevel::Info);

        logger.error("Something went wrong")?;

        logger.info("This should use default format")?;
        logger.warning("This should also use default format")?;

        Ok(())
    }

    #[test]
    fn test_log_level_filtering() -> io::Result<()> {
        let (logger, _cursor) = create_test_logger_with_level(LogLevel::Warning);

        assert_eq!(logger.level(), LogLevel::Warning);

        logger.info("This should not appear")?;
        logger.debug("This should not appear")?;
        logger.trace("This should not appear")?;

        logger.warning("This should appear")?;
        logger.error("This should also appear")?;

        assert_eq!(logger.level(), LogLevel::Warning);

        Ok(())
    }

    #[test]
    fn test_multiple_loggers() -> io::Result<()> {
        let (logger1, _cursor1) = create_test_logger();
        let (logger2, _cursor2) = create_test_logger_with_level(LogLevel::Warning);

        assert_eq!(logger1.level(), LogLevel::Info);
        assert_eq!(logger2.level(), LogLevel::Warning);

        logger1.info("Message from logger 1")?;
        logger2.warning("Message from logger 2")?;

        logger1.info("Another message from logger 1")?;

        logger2.info("This should be filtered by logger 2")?;

        assert_eq!(logger1.level(), LogLevel::Info);
        assert_eq!(logger2.level(), LogLevel::Warning);

        Ok(())
    }

    #[test]
    fn test_lazy_logging_execution() -> io::Result<()> {
        let (logger, _cursor) = create_test_logger_with_level(LogLevel::Info);

        let mut expensive_called = false;

        logger.debug_lazy(|| {
            expensive_called = true;
            "This should not be computed".to_string()
        })?;

        assert!(
            !expensive_called,
            "Expensive computation should not have been called"
        );

        expensive_called = false;

        logger.info_lazy(|| {
            expensive_called = true;
            "This should be computed".to_string()
        })?;

        assert!(
            expensive_called,
            "Expensive computation should have been called"
        );

        Ok(())
    }

    #[test]
    fn test_lazy_logging_with_expensive_computation() -> io::Result<()> {
        let (logger, _cursor) = create_test_logger_with_level(LogLevel::Warning);

        use std::cell::RefCell;
        let computation_count = RefCell::new(0);

        logger.trace_lazy(|| {
            *computation_count.borrow_mut() += 1;
            "Trace message".to_string()
        })?;
        logger.debug_lazy(|| {
            *computation_count.borrow_mut() += 1;
            "Debug message".to_string()
        })?;
        logger.info_lazy(|| {
            *computation_count.borrow_mut() += 1;
            "Info message".to_string()
        })?;

        assert_eq!(
            *computation_count.borrow(),
            0,
            "No expensive computations should have been executed"
        );

        logger.warning_lazy(|| {
            *computation_count.borrow_mut() += 1;
            "Warning message".to_string()
        })?;
        assert_eq!(
            *computation_count.borrow(),
            1,
            "One expensive computation should have been executed"
        );

        logger.error_lazy(|| {
            *computation_count.borrow_mut() += 1;
            "Error message".to_string()
        })?;
        assert_eq!(
            *computation_count.borrow(),
            2,
            "Two expensive computations should have been executed"
        );

        Ok(())
    }

    #[test]
    fn test_lazy_logging_vs_regular_logging() -> io::Result<()> {
        let (logger, _cursor) = create_test_logger_with_level(LogLevel::Warning);
        let mut lazy_called = false;

        logger.warning_lazy(|| {
            lazy_called = true;
            "Lazy warning".to_string()
        })?;

        logger.warning("Regular warning")?;
        assert!(lazy_called, "Lazy closure should have been called");

        Ok(())
    }

    #[test]
    fn test_multi_target_logging() -> io::Result<()> {
        let (logger, _cursor) = create_test_logger();

        logger.info("Test message for multi-target logging")?;

        Ok(())
    }

    #[test]
    fn test_multi_target_lazy_logging() -> io::Result<()> {
        let (logger, _cursor) = create_test_logger();

        let mut call_count = 0;

        logger.info_lazy(|| {
            call_count += 1;
            "Lazy message for multiple targets".to_string()
        })?;

        assert_eq!(call_count, 1, "Lazy closure should be called only once");

        Ok(())
    }

    #[test]
    fn test_log_output_verification() -> io::Result<()> {
        let (logger, buffer) = create_capturable_test_logger();

        logger.info("Test message")?;

        std::thread::sleep(std::time::Duration::from_millis(10));

        let captured = buffer.lock().unwrap();
        let output = String::from_utf8_lossy(&captured);

        assert!(
            output.contains("Test message"),
            "Output should contain the log message"
        );
        assert!(
            output.contains("[INFO]"),
            "Output should contain the log level"
        );

        Ok(())
    }

    #[test]
    fn test_custom_format_output_verification() -> io::Result<()> {
        let (mut logger, buffer) = create_capturable_test_logger();

        logger
            .format_strings
            .insert(LogLevel::Error, "ERROR: {message}".to_string());

        logger.error("Something went wrong")?;

        std::thread::sleep(std::time::Duration::from_millis(10));

        let captured = buffer.lock().unwrap();
        let output = String::from_utf8_lossy(&captured);

        assert!(
            output.contains("ERROR: Something went wrong"),
            "Output should contain the custom formatted message"
        );

        Ok(())
    }

    #[test]
    fn test_format_sets_same_format_for_all_levels_output() -> io::Result<()> {
        const LOG_PREFIX: &str = "worker-1";

        let (logger, buffer) = create_capturable_test_logger();
        let logger = logger.format(format!("[{{level}}][{}] {{message}}", LOG_PREFIX));

        logger.error("Error message")?;
        logger.info("Info message")?;

        std::thread::sleep(std::time::Duration::from_millis(10));

        let captured = buffer.lock().unwrap();
        let output = String::from_utf8_lossy(&captured);

        assert!(
            output.contains("[ERROR][worker-1] Error message"),
            "Output should contain formatted error message with prefix"
        );
        assert!(
            output.contains("[INFO][worker-1] Info message"),
            "Output should contain formatted info message with prefix"
        );

        Ok(())
    }
}