Skip to main content

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
61use std::{env, io::Write};
62
63use colored::*;
64use env_logger::Builder;
65use log::LevelFilter;
66
67/// ```rust
68/// use crate::Maintain::Source::Build::Logger;
69/// Logger();
70/// log::info!("Logger initialized");
71/// ```
72// Example 2: Setting custom log level
73/// ```sh
74/// export RUST_LOG=debug
75/// ./build-script --name MyApp pnpm build
76/// ```
77//
78//=============================================================================//
79// IMPLEMENTATION
80//=============================================================================//
81use crate::Build::Constant::LogEnv;
82
83/// Sets up the global logger for the application.
84///
85/// This function initializes the `env_logger` crate with custom formatting
86/// and configuration for the build system. It:
87///
88/// - Reads the `RUST_LOG` environment variable to set the log level
89/// - Defaults to `info` level if the variable is not set
90/// - Provides color-coded output for different log levels
91/// - Formats messages with a consistent `[Build]` prefix
92///
93/// # Log Levels
94///
95/// Supported log levels (in increasing verbosity):
96/// - `error` - Only error messages
97/// - `warn` - Warning messages and errors
98/// - `info` - Informational messages, warnings, and errors (default)
99/// - `debug` - Debug messages and above
100/// - `trace` - Trace messages and above (very verbose)
101///
102/// # Log Format
103///
104/// Messages are formatted as:
105/// ```
106/// [Build] [LEVEL]: message content
107/// ```
108///
109/// Where `LEVEL` is color-coded:
110/// - `[ERROR]` - Red, bold
111/// - `[WARN]` - Yellow, bold
112/// - `[INFO]` - Green
113/// - `[DEBUG]` - Blue
114/// - `[TRACE]` - Magenta
115///
116/// # Environment Configuration
117///
118/// The log level is controlled by the `RUST_LOG` environment variable:
119///
120/// ```sh
121/// Set minimum log level to debug
122/// export RUST_LOG=debug
123///
124/// Enable debug logs only for the Build module
125/// export RUST_LOG=Build=debug
126///
127/// Enable trace logs for Build::Toml module
128/// export RUST_LOG=Build::Toml=trace
129/// ```
130///
131/// # Usage Example
132///
133/// ```no_run
134/// use log::{error, info};
135///
136/// use crate::Maintain::Source::Build::Logger;
137///
138/// // Initialize logger first
139/// Logger();
140///
141/// // Now logging is available throughout the application
142/// info!("Build process started");
143/// error!("Build process failed");
144/// ```
145///
146/// # Module-Specific Logging
147///
148/// The build system uses the following logging targets:
149/// - `Build` - General build orchestration messages
150/// - `Build::Guard` - File backup and restoration messages
151/// - `Build::Toml` - TOML editing messages
152/// - `Build::Json` - JavaScriptObjectNotation editing messages
153/// - `Build::Exec` - Command execution messages
154///
155/// You can set different log levels for each target:
156/// ```sh
157/// export RUST_LOG=Build=info,Build::Toml=debug,Build::Exec=warn
158/// ```
159///
160/// # Thread Safety
161///
162/// The global logger initialized by this function is thread-safe and can be
163/// used from multiple threads concurrently without additional synchronization.
164///
165/// # Implementation Notes
166///
167/// This function uses `env_logger::Builder` to construct the logger with
168/// custom formatting. The formatter uses the `colored` crate to apply
169/// color coding based on the log level.
170///
171/// The logger is typically called once at program startup, before any other
172/// operations that might generate log messages.
173pub fn Logger() {
174	let LevelText = env::var(LogEnv).unwrap_or_else(|_| "info".to_string());
175
176	let LogLevel = LevelText.parse::<LevelFilter>().unwrap_or(LevelFilter::Info);
177
178	Builder::new()
179		.filter_level(LogLevel)
180		.format(|Buffer, Record| {
181			let LevelStyle = match Record.level() {
182				log::Level::Error => "ERROR".red().bold(),
183
184				log::Level::Warn => "WARN".yellow().bold(),
185
186				log::Level::Info => "INFO".green(),
187
188				log::Level::Debug => "DEBUG".blue(),
189
190				log::Level::Trace => "TRACE".magenta(),
191			};
192
193			writeln!(Buffer, "[{}] [{}]: {}", "Build".red(), LevelStyle, Record.args())
194		})
195		.parse_default_env()
196		.init();
197}