pub fn init_logger_from_env<P: AsRef<Path>>(
file_path: Option<P>,
) -> Result<(), LogError>Expand description
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 debugmy_crate=debug- Set specific module to debugmy_crate::module=trace- Set submodule to tracemy_crate=debug,other_crate::module=trace- Multiple module filterswarn- Set default level to warn
§Arguments
file_path- Optional path to a log file. IfNone, logs will only go to stdout.
§Returns
Ok(()) if initialization succeeded, or an error if it failed.
§Example
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");Examples found in repository?
examples/module_filters.rs (line 69)
67fn main() {
68 // Initialize logger from RUST_LOG environment variable
69 if let Err(e) = init_logger_from_env(Some("module_filters.log")) {
70 eprintln!("Failed to initialize logger: {e}");
71 return;
72 }
73
74 println!("=== Module Filters Example ===");
75 println!("Current RUST_LOG: {:?}", std::env::var("RUST_LOG").unwrap_or_else(|_| "not set".to_string()));
76 println!("\nTry running with different RUST_LOG values:");
77 println!(" RUST_LOG=debug cargo run --example module_filters");
78 println!(" RUST_LOG=trace cargo run --example module_filters");
79 println!(" RUST_LOG=module_filters::network=trace,warn cargo run --example module_filters");
80 println!(" RUST_LOG=module_filters::database=error cargo run --example module_filters");
81 println!("\n--- Application Logs ---\n");
82
83 // Main application logs
84 info!("Application starting...");
85 debug!("Debug mode enabled");
86 trace!("This is a trace message from main");
87
88 // Network module operations
89 info!("Testing network module:");
90 network::connect();
91 network::send_data();
92
93 // Database module operations
94 info!("\nTesting database module:");
95 database::query();
96 database::transaction();
97
98 // Cache module operations
99 info!("\nTesting cache module:");
100 cache::get("user:123");
101 cache::set("user:123");
102
103 // More main application logs
104 warn!("This is a warning from main");
105 error!("This is an error from main");
106
107 info!("\nApplication finished");
108 println!("\n--- End of Logs ---");
109 println!("\nCheck 'module_filters.log' for complete log output.");
110}