Maintain/Build/
Logger.rs

1//=============================================================================//
2// File Path: Element/Maintain/Source/Build/Logger.rs
3//=============================================================================//
4// Module: Logger
5//
6// Brief Description: Initializes the global logger for the build system.
7//
8// RESPONSIBILITIES:
9// ================
10//
11// Primary:
12// - Initialize the environment logger with colored output
13// - Configure log level based on environment variable
14// - Format log messages consistent with the build system style
15//
16// Secondary:
17// - Support module-level log filtering
18// - Provide color-coded log levels
19//
20// ARCHITECTURAL ROLE:
21// ===================
22//
23// Position:
24// - Infrastructure/Logging layer
25// - Logging system initialization
26//
27// Dependencies (What this module requires):
28// - External crates: env_logger, log, colored
29// - Internal modules: Constant::LogEnvironmentConstant
30// - Traits implemented: None
31//
32// Dependents (What depends on this module):
33// - Main entry point
34// - Initialize function
35//
36// IMPLEMENTATION DETAILS:
37// =======================
38//
39// Design Patterns:
40// - Singleton pattern (global logger)
41// - Initialization function pattern
42//
43// Performance Considerations:
44// - Complexity: O(1) - single initialization
45// - Memory usage patterns: Minimal overhead for logging infrastructure
46// - Hot path optimizations: None needed (logging is infrequent)
47//
48// Thread Safety:
49// - Thread-safe: Yes (env_logger is thread-safe)
50// - Synchronization mechanisms used: Internal to env_logger
51// - Interior mutability considerations: None
52//
53// Error Handling:
54// - Error types returned: None (panics are handled by env_logger)
55// - Recovery strategies: Not applicable (logger must be initialized once)
56//
57// EXAMPLES:
58// =========
59//
60// Example 1: Basic logger initialization
61/// ```rust
62/// use crate::Maintain::Source::Build::Logger;
63/// Logger();
64/// log::info!("Logger initialized");
65/// ```
66//
67// Example 2: Setting custom log level
68/// ```sh
69/// export RUST_LOG=debug
70/// ./build-script --name MyApp pnpm build
71/// ```
72//
73//=============================================================================//
74// IMPLEMENTATION
75//=============================================================================//
76
77use crate::Build::Constant::LogEnv;
78
79use colored::*;
80use env_logger::Builder;
81use log::LevelFilter;
82use std::env;
83use std::io::Write;
84
85/// Sets up the global logger for the application.
86///
87/// This function initializes the `env_logger` crate with custom formatting
88/// and configuration for the build system. It:
89///
90/// - Reads the `RUST_LOG` environment variable to set the log level
91/// - Defaults to `info` level if the variable is not set
92/// - Provides color-coded output for different log levels
93/// - Formats messages with a consistent `[Build]` prefix
94///
95/// # Log Levels
96///
97/// Supported log levels (in increasing verbosity):
98/// - `error` - Only error messages
99/// - `warn` - Warning messages and errors
100/// - `info` - Informational messages, warnings, and errors (default)
101/// - `debug` - Debug messages and above
102/// - `trace` - Trace messages and above (very verbose)
103///
104/// # Log Format
105///
106/// Messages are formatted as:
107/// ```
108/// [Build] [LEVEL]: message content
109/// ```
110///
111/// Where `LEVEL` is color-coded:
112/// - `[ERROR]` - Red, bold
113/// - `[WARN]` - Yellow, bold
114/// - `[INFO]` - Green
115/// - `[DEBUG]` - Blue
116/// - `[TRACE]` - Magenta
117///
118/// # Environment Configuration
119///
120/// The log level is controlled by the `RUST_LOG` environment variable:
121///
122/// ```sh
123/// Set minimum log level to debug
124/// export RUST_LOG=debug
125///
126/// Enable debug logs only for the Build module
127/// export RUST_LOG=Build=debug
128///
129/// Enable trace logs for Build::Toml module
130/// export RUST_LOG=Build::Toml=trace
131/// ```
132///
133/// # Usage Example
134///
135/// ```no_run
136/// use crate::Maintain::Source::Build::Logger;
137/// use log::{info, error};
138///
139/// // Initialize logger first
140/// Logger();
141///
142/// // Now logging is available throughout the application
143/// info!("Build process started");
144/// error!("Build process failed");
145/// ```
146///
147/// # Module-Specific Logging
148///
149/// The build system uses the following logging targets:
150/// - `Build` - General build orchestration messages
151/// - `Build::Guard` - File backup and restoration messages
152/// - `Build::Toml` - TOML editing messages
153/// - `Build::Json` - JavaScriptObjectNotation editing messages
154/// - `Build::Exec` - Command execution messages
155///
156/// You can set different log levels for each target:
157/// ```sh
158/// export RUST_LOG=Build=info,Build::Toml=debug,Build::Exec=warn
159/// ```
160///
161/// # Thread Safety
162///
163/// The global logger initialized by this function is thread-safe and can be
164/// used from multiple threads concurrently without additional synchronization.
165///
166/// # Implementation Notes
167///
168/// This function uses `env_logger::Builder` to construct the logger with
169/// custom formatting. The formatter uses the `colored` crate to apply
170/// color coding based on the log level.
171///
172/// The logger is typically called once at program startup, before any other
173/// operations that might generate log messages.
174pub fn Logger() {
175    let LevelText = env::var(LogEnv).unwrap_or_else(|_| "info".to_string());
176
177    let LogLevel = LevelText.parse::<LevelFilter>().unwrap_or(LevelFilter::Info);
178
179    Builder::new()
180        .filter_level(LogLevel)
181        .format(|Buffer, Record| {
182            let LevelStyle = match Record.level() {
183                log::Level::Error => "ERROR".red().bold(),
184
185                log::Level::Warn => "WARN".yellow().bold(),
186
187                log::Level::Info => "INFO".green(),
188
189                log::Level::Debug => "DEBUG".blue(),
190
191                log::Level::Trace => "TRACE".magenta(),
192            };
193
194            writeln!(Buffer, "[{}] [{}]: {}", "Build".red(), LevelStyle, Record.args())
195        })
196        .parse_default_env()
197        .init();
198}