basic_usage/
basic_usage.rs

1// This example demonstrates the core functionality of the fstdout-logger crate.
2//
3// Features shown:
4// - Using the builder pattern to create a custom logger configuration
5// - Logging to both stdout and a file simultaneously
6// - Using all log levels (trace, debug, info, warn, error)
7// - Colored console output with timestamps
8// - Complete log file with timestamps and source location
9
10use fstdout_logger::{LoggerConfig, init_logger_with_config};
11use log::{LevelFilter, debug, error, info, trace, warn};
12use std::thread::sleep;
13use std::time::Duration;
14
15fn main() {
16    // Initialize logger with file output and colored stdout
17    let log_path = "application.log";
18
19    // Create a custom configuration with the builder pattern
20    // This shows how to configure every aspect of the logger
21    let config = LoggerConfig::builder()
22        .level(LevelFilter::Trace) // Show all log levels, including TRACE
23        .show_file_info(true) // Include file and line info in logs
24        .show_date_in_stdout(false) // Only show time (HH:MM:SS) in console output
25        .use_colors(true) // Use colors for different log levels
26        .build();
27
28    if let Err(e) = init_logger_with_config(Some(log_path), config) {
29        eprintln!("Failed to initialize logger: {e}");
30        return;
31    }
32
33    println!("Logger initialized! Check {log_path} for log output.");
34    println!("Log messages will appear both on stdout and in the log file.");
35    println!("Notice that stdout logs show time only while the file includes dates.");
36
37    // Log messages at different levels to demonstrate the hierarchy
38    // All of these will appear because we set level to Trace
39    trace!("This is a TRACE message"); // Lowest level, normally hidden
40    debug!("This is a DEBUG message"); // For developer information
41    info!("This is an INFO message"); // Normal application events
42    warn!("This is a WARNING message"); // Important but non-critical issues
43    error!("This is an ERROR message"); // Critical issues that need attention
44
45    // Simulate some application activity
46    for i in 1..=5 {
47        info!("Application is running... iteration {i}");
48        sleep(Duration::from_millis(500));
49    }
50
51    // Log a final message
52    info!("Application finished successfully");
53
54    println!("\nAfter running this example, check the 'application.log' file");
55    println!("to see how logs are formatted differently for file output.");
56}