Set log level on the command line
It is nice that one can set the log-level using the RUST_LOG environment variable, but if your project already has various command-line options then it seem to make sense to be able to set
the log level via a command-line flag as well. Here is one way to do it using the env_logger and the log crates.
use clap::Parser;
#[derive(Parser, Debug)]
#[command(version)]
struct Cli {
#[arg(long, help = "Set logging level (debug, info, warn, error). Default is 'warn'")]
log: Option<log::Level>,
}
fn main() {
let args = Cli::parse();
let mut builder = env_logger::Builder::new();
let log_level = if let Some(level) = args.log {
level.to_string()
} else {
std::env::var("RUST_LOG").unwrap_or(String::from("warn"))
};
builder.parse_filters(&log_level);
builder.init();
log::debug!("Debug level log");
log::info!("Info level log");
log::warn!("Warn level log");
log::error!("Error level log");
}
Try some of the following commands:
The default log level is “warn”:
cargo run
Set the log level to debug using the command line:
cargo run -- --log debug
Set the log level to info using the environment variable:
RUST_LOG=info cargo run
Set the log level to debug using the command line:
The command-line option overrides the environment variable.
RUST_LOG=info cargo run -- --log debug
Invalid log-levels will be stopped when parsing the command-line argument list:
cargo run -- --log duck
[package]
name = "env-logger-set-log-level-on-the-command-line"
version = "0.1.0"
edition = "2024"
[dependencies]
clap = { version = "4.5.49", features = ["derive"] }
env_logger = "0.11.8"
log = "0.4.28"
serde = { version = "1.0.228", features = ["derive"] }