fstdout-logger 0.2.2

An implementation of the log crate that logs to stdout and to an optional log file with configurable options.
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
//! # FStdout Logger
//!
//! A flexible logger implementation for Rust that logs to both stdout and a file,
//! with support for colored console output and customizable formatting.
//!
//! ## Key Features
//!
//! - Log to both stdout and a file simultaneously
//! - Colored terminal output (configurable)
//! - Minimal stdout formatting (timestamp without date by default)
//! - Full file logging with timestamps and source location
//! - Multiple configuration options and presets
//!
//! ## Basic Usage
//!
//! ```rust
//! use fstdout_logger::init_logger;
//! use log::info;
//!
//! // Initialize with defaults (Info level, colors enabled, file info shown)
//! init_logger(Some("application.log")).expect("Failed to initialize logger");
//!
//! info!("Application started");
//! ```
//!
//! ## Configuration Options
//!
//! The logger can be customized using the `LoggerConfig` struct:
//!
//! ```rust
//! use fstdout_logger::{init_logger_with_config, LoggerConfig};
//! use log::LevelFilter;
//!
//! // Create a custom configuration
//! let config = LoggerConfig::builder()
//!     .level(LevelFilter::Debug)
//!     .show_file_info(false)      // Don't show file paths in stdout
//!     .show_date_in_stdout(false) // Show only time, not date in stdout
//!     .use_colors(true)           // Use colored output in terminal
//!     .build();
//!
//! init_logger_with_config(Some("debug.log"), config).expect("Failed to initialize logger");
//! ```
//!
//! ## Presets
//!
//! The library provides convenient presets for common scenarios:
//!
//! ```rust
//! // For development (Debug level, file info shown)
//! fstdout_logger::init_development_logger(Some("dev.log")).expect("Failed to initialize logger");
//!
//! // For production (Info level, no file info)
//! fstdout_logger::init_production_logger(Some("app.log")).expect("Failed to initialize logger");
//! ```

use flate2::Compression;
use log::{LevelFilter, Log, Metadata, Record};
use std::fs::{File, OpenOptions, create_dir_all};
use std::io::{self, Write};
use std::path::Path;
use std::sync::Mutex;
use thiserror::Error;

mod config;
pub mod examples;
pub mod formatter;

pub use config::{LoggerConfig, LoggerConfigBuilder, ModuleFilters};
pub use formatter::LogFormatter;

/// Errors that can occur when using the logger.
#[derive(Error, Debug)]
pub enum LogError {
    /// I/O errors when opening or writing to log files.
    #[error("IO error: {0}")]
    Io(#[from] io::Error),

    /// Errors when setting up the global logger.
    #[error("Failed to set logger")]
    Logger,
}

/// The main logger implementation that outputs to stdout and optionally to a file.
///
/// This struct implements the [`Log`] trait from the standard `log` crate,
/// handling log messages by:
///
/// 1. Writing to stdout with optional colors and formatting
/// 2. Writing to a file (if configured) with full details
///
/// # Example
///
/// ```rust
/// use fstdout_logger::{FStdoutLogger, LoggerConfig};
/// use log::LevelFilter;
///
/// // Creating a logger directly (usually done via helper functions)
/// let logger = FStdoutLogger::with_config(
///     Some("app.log"),
///     LoggerConfig::default()
/// ).expect("Failed to create logger");
///
/// // Initialize as the global logger
/// logger.init_with_level(LevelFilter::Info).expect("Failed to initialize logger");
/// ```
pub struct FStdoutLogger {
    /// Optional file to log to
    log_file: Option<Mutex<File>>,

    /// Formatter for log messages
    formatter: LogFormatter,
}

impl FStdoutLogger {
    /// Create a new logger with default configuration.
    ///
    /// This is a convenience method that uses [`LoggerConfig::default()`].
    ///
    /// # Arguments
    ///
    /// * `file_path` - Optional path to a log file. If `None`, logs will only go to stdout.
    ///
    /// # Returns
    ///
    /// A new logger instance or an error if the log file couldn't be opened.
    pub fn new<P: AsRef<Path>>(file_path: Option<P>) -> Result<Self, LogError> {
        Self::with_config(file_path, LoggerConfig::default())
    }

    /// Create a new logger with custom configuration.
    ///
    /// # Arguments
    ///
    /// * `file_path` - Optional path to a log file. If `None`, logs will only go to stdout.
    /// * `config` - Configuration options for the logger.
    ///
    /// # Returns
    ///
    /// A new logger instance or an error if the log file couldn't be opened.
    pub fn with_config<P: AsRef<Path>>(
        file_path: Option<P>,
        config: LoggerConfig,
    ) -> Result<Self, LogError> {
        let log_file = match file_path {
            Some(path) => {
                let file = Path::new(path.as_ref()).to_path_buf();
                if let Some(parent) = file.parent() {
                    create_dir_all(parent)?;
                };
                if file.exists() {
                    use flate2::write::GzEncoder;
                    use tar::Builder;

                    let file_basename = format!("{}", chrono::Local::now().format("%d%m%Y_%H%M%S"));
                    let archive_ref = format!("{}.tar.xz", file_basename);
                    let mut archive_path = Path::new(&archive_ref).to_path_buf();
                    if let Some(parent) = file.parent() {
                        archive_path = parent.join(archive_path.file_name().unwrap());
                    };
                    let archive_file = File::create(archive_path)?;

                    let encoder = GzEncoder::new(archive_file, Compression::default());
                    let mut archive = Builder::new(encoder);

                    archive.append_file(
                        Path::new(&format!("{}.log", file_basename)),
                        &mut File::open(file)?,
                    )?;

                    archive.into_inner().unwrap();
                }
                let file = OpenOptions::new()
                    .create(true)
                    .truncate(true)
                    .write(true)
                    .open(path)?;
                Some(Mutex::new(file))
            }
            None => None,
        };

        Ok(Self {
            log_file,
            formatter: LogFormatter::new(config),
        })
    }

    /// Initialize the logger with the default configuration.
    ///
    /// This sets the maximum log level to `Trace` to enable all logs,
    /// but actual filtering will happen according to the `level` setting
    /// in the logger's configuration.
    ///
    /// # Returns
    ///
    /// `Ok(())` if initialization succeeded, or an error if it failed.
    pub fn init(self) -> Result<(), LogError> {
        if log::set_logger(Box::leak(Box::new(self))).is_err() {
            return Err(LogError::Logger);
        }
        log::set_max_level(LevelFilter::Trace);
        Ok(())
    }

    /// Initialize the logger with a specific log level.
    ///
    /// This sets the global maximum log level, overriding the level
    /// in the logger's configuration.
    ///
    /// # Arguments
    ///
    /// * `level` - The minimum log level to display.
    ///
    /// # Returns
    ///
    /// `Ok(())` if initialization succeeded, or an error if it failed.
    pub fn init_with_level(self, level: LevelFilter) -> Result<(), LogError> {
        if log::set_logger(Box::leak(Box::new(self))).is_err() {
            return Err(LogError::Logger);
        }
        log::set_max_level(level);
        Ok(())
    }
}

/// Implementation of the `Log` trait for `FStdoutLogger`.
///
/// This handles:
/// - Checking if a log message should be processed (with module-level filtering)
/// - Formatting messages differently for stdout and file
/// - Writing to both destinations
/// - Flushing output streams
impl Log for FStdoutLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        // First check global max level
        if metadata.level() > log::max_level() {
            return false;
        }

        // Then check module-specific filters
        let target = metadata.target();
        let module_level = self.formatter.config().module_filters.level_for(target);

        metadata.level() <= module_level
    }

    fn log(&self, record: &Record) {
        if !self.enabled(record.metadata()) {
            return;
        }

        // Format for stdout (with or without colors)
        let stdout_formatted = format!("{}\n", self.formatter.format_stdout(record));

        // Log to stdout
        print!("{stdout_formatted}");

        // Log to file if configured
        if let Some(file) = &self.log_file
            && let Ok(mut file) = file.lock()
        {
            // Format for file (always without colors)
            let file_formatted = self.formatter.format_file(record);

            // Ignore errors when writing to file as we don't want to crash the application
            let _ = file.write_all(file_formatted.as_bytes());
        }
    }

    fn flush(&self) {
        // Flush stdout
        let _ = io::stdout().flush();

        // Flush file if configured
        if let Some(file) = &self.log_file
            && let Ok(mut file) = file.lock()
        {
            let _ = file.flush();
        }
    }
}

//
// Helper functions for easily initializing the logger
//

/// Initialize a logger with default configuration.
///
/// This automatically reads from environment variables:
/// - `RUST_LOG` for module-level filtering
/// - `LOG_LEVEL` for numeric log level (0-5)
///
/// If neither is set, defaults to Info level with standard settings.
///
/// # Arguments
///
/// * `file_path` - Optional path to a log file. If `None`, logs will only go to stdout.
///
/// # Returns
///
/// `Ok(())` if initialization succeeded, or an error if it failed.
///
/// # Example
///
/// ```rust
/// use fstdout_logger::init_logger;
/// use log::info;
///
/// init_logger(Some("app.log")).expect("Failed to initialize logger");
/// info!("Logger initialized with environment variable support");
/// ```
pub fn init_logger<P: AsRef<Path>>(file_path: Option<P>) -> Result<(), LogError> {
    // Check if environment variables are set
    if std::env::var("RUST_LOG").is_ok() || std::env::var("LOG_LEVEL").is_ok() {
        // Use from_env if any environment variable is set
        init_logger_from_env(file_path)
    } else {
        // Use default configuration
        FStdoutLogger::new(file_path)?.init()
    }
}

/// Initialize a logger with a specific log level.
///
/// This uses the default configuration but overrides the log level.
///
/// # Arguments
///
/// * `file_path` - Optional path to a log file. If `None`, logs will only go to stdout.
/// * `level` - The minimum log level to display.
///
/// # Returns
///
/// `Ok(())` if initialization succeeded, or an error if it failed.
///
/// # Example
///
/// ```rust
/// use fstdout_logger::init_logger_with_level;
/// use log::LevelFilter;
///
/// init_logger_with_level(Some("debug.log"), LevelFilter::Debug)
///     .expect("Failed to initialize logger");
/// ```
pub fn init_logger_with_level<P: AsRef<Path>>(
    file_path: Option<P>,
    level: LevelFilter,
) -> Result<(), LogError> {
    FStdoutLogger::new(file_path)?.init_with_level(level)
}

/// Initialize a logger with custom configuration.
///
/// This gives full control over all configuration options.
///
/// # Arguments
///
/// * `file_path` - Optional path to a log file. If `None`, logs will only go to stdout.
/// * `config` - Configuration options for the logger.
///
/// # Returns
///
/// `Ok(())` if initialization succeeded, or an error if it failed.
///
/// # Example
///
/// ```rust
/// use fstdout_logger::{init_logger_with_config, LoggerConfig};
/// use log::LevelFilter;
///
/// // Create a custom configuration
/// let config = LoggerConfig::builder()
///     .level(LevelFilter::Debug)
///     .show_file_info(false)
///     .use_colors(true)
///     .build();
///
/// init_logger_with_config(Some("app.log"), config)
///     .expect("Failed to initialize logger");
/// ```
pub fn init_logger_with_config<P: AsRef<Path>>(
    file_path: Option<P>,
    config: LoggerConfig,
) -> Result<(), LogError> {
    let level = config.level;
    FStdoutLogger::with_config(file_path, config)?.init_with_level(level)
}

/// Initialize a production-ready logger (no file info, concise format).
///
/// This uses [`LoggerConfig::production()`] which is optimized for
/// clean, minimal output in production environments:
/// - `Info` as the minimum log level (no debug messages)
/// - No file information shown in logs
/// - No date in stdout output (only time)
/// - Colors enabled for better readability
///
/// # Arguments
///
/// * `file_path` - Optional path to a log file. If `None`, logs will only go to stdout.
///
/// # Returns
///
/// `Ok(())` if initialization succeeded, or an error if it failed.
///
/// # Example
///
/// ```rust
/// use fstdout_logger::init_production_logger;
///
/// init_production_logger(Some("app.log"))
///     .expect("Failed to initialize production logger");
/// ```
pub fn init_production_logger<P: AsRef<Path>>(file_path: Option<P>) -> Result<(), LogError> {
    init_logger_with_config(file_path, LoggerConfig::production())
}

/// Initialize a development logger (with file info, colored output).
///
/// This uses [`LoggerConfig::development()`] which is optimized for
/// detailed output during development:
/// - `Debug` as the minimum log level (shows debug messages)
/// - File information shown in logs (helps with debugging)
/// - No date in stdout output (only time)
/// - Colors enabled for better readability
///
/// # Arguments
///
/// * `file_path` - Optional path to a log file. If `None`, logs will only go to stdout.
///
/// # Returns
///
/// `Ok(())` if initialization succeeded, or an error if it failed.
///
/// # Example
///
/// ```rust
/// use fstdout_logger::init_development_logger;
///
/// init_development_logger(Some("debug.log"))
///     .expect("Failed to initialize development logger");
/// ```
pub fn init_development_logger<P: AsRef<Path>>(file_path: Option<P>) -> Result<(), LogError> {
    init_logger_with_config(file_path, LoggerConfig::development())
}

/// Initialize a logger that only writes to stdout (not to a file).
///
/// # Arguments
///
/// * `config` - Configuration options for the logger.
///
/// # Returns
///
/// `Ok(())` if initialization succeeded, or an error if it failed.
///
/// # Example
///
/// ```rust
/// use fstdout_logger::{init_stdout_logger, LoggerConfig};
///
/// init_stdout_logger(LoggerConfig::default())
///     .expect("Failed to initialize stdout logger");
/// ```
pub fn init_stdout_logger(config: LoggerConfig) -> Result<(), LogError> {
    init_logger_with_config(None::<String>, config)
}

/// Initialize a minimal stdout-only logger with just the specified level.
///
/// This is the simplest way to get a stdout-only logger with a specific level.
///
/// # Arguments
///
/// * `level` - The minimum log level to display.
///
/// # Returns
///
/// `Ok(())` if initialization succeeded, or an error if it failed.
///
/// # Example
///
/// ```rust
/// use fstdout_logger::init_simple_stdout_logger;
/// use log::LevelFilter;
///
/// init_simple_stdout_logger(LevelFilter::Info)
///     .expect("Failed to initialize simple logger");
/// ```
pub fn init_simple_stdout_logger(level: LevelFilter) -> Result<(), LogError> {
    // Create a minimal config with the specified level
    let config = LoggerConfig {
        level,
        ..LoggerConfig::default()
    };

    // Initialize with the config
    FStdoutLogger::with_config(None::<String>, config)?.init_with_level(level)
}

/// Initialize a logger from the RUST_LOG environment variable.
///
/// This reads the RUST_LOG environment variable to configure log levels
/// and module-specific filters. If RUST_LOG is not set, defaults to Info level.
///
/// # Supported RUST_LOG formats
///
/// - `debug` - Set default level to debug
/// - `my_crate=debug` - Set specific module to debug
/// - `my_crate::module=trace` - Set submodule to trace
/// - `my_crate=debug,other_crate::module=trace` - Multiple module filters
/// - `warn` - Set default level to warn
///
/// # Arguments
///
/// * `file_path` - Optional path to a log file. If `None`, logs will only go to stdout.
///
/// # Returns
///
/// `Ok(())` if initialization succeeded, or an error if it failed.
///
/// # Example
///
/// ```rust
/// use fstdout_logger::init_logger_from_env;
///
/// // Set RUST_LOG=debug or RUST_LOG=my_crate=trace,other=warn
/// init_logger_from_env(Some("app.log"))
///     .expect("Failed to initialize logger");
/// ```
pub fn init_logger_from_env<P: AsRef<Path>>(file_path: Option<P>) -> Result<(), LogError> {
    let config = LoggerConfig::from_env();
    // Always use Trace as max level to allow module filters to work correctly
    FStdoutLogger::with_config(file_path, config)?.init()
}

#[cfg(test)]
mod tests {
    use super::*;
    use log::{debug, error, info, trace, warn};
    use std::fs;
    use std::io::Read;

    #[test]
    fn test_stdout_logger() {
        // This test only checks that initialization doesn't fail
        let config = LoggerConfig::builder()
            .level(LevelFilter::Debug)
            .show_file_info(false)
            .build();

        let result = init_stdout_logger(config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_file_logger() {
        let test_file = "test_log.txt";
        // Clean up any existing test file
        let _ = fs::remove_file(test_file);

        // Initialize logger
        let config = LoggerConfig::builder()
            .level(LevelFilter::Debug)
            .show_file_info(true)
            .use_colors(false)
            .build();

        let result = init_logger_with_config(Some(test_file), config);
        assert!(result.is_ok());

        // Log some messages
        trace!("This is a trace message");
        debug!("This is a debug message");
        info!("This is an info message");
        warn!("This is a warning message");
        error!("This is an error message");

        // Verify file contains logs
        let mut file = File::open(test_file).expect("Failed to open log file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read log file");

        // Debug and higher should be logged
        assert!(!contents.contains("trace message"));
        assert!(contents.contains("debug message"));
        assert!(contents.contains("info message"));
        assert!(contents.contains("warning message"));
        assert!(contents.contains("error message"));

        // Clean up
        let _ = fs::remove_file(test_file);
    }
}