env_logger is a simple logging implementation that allows you to control logs to stdout or stderr through the RUST_LOG environment variable. The values of this environment variable are comma-separated logger strings that correspond to module names and log levels. To demonstrate env_logger, we'll create a new binary crate by running cargo new env_logger_demo and specifying dependencies for log, env_logger, and our user_auth library, which we created in the previous section. Here's our Cargo.toml file:
# env_logger_demo/Cargo.toml
[dependencies]
env_logger = "0.6.0"
user_auth = { path = "../user_auth" }
log = { version = "0.4.6", features = ["release_max_level_error", "max_level_trace"] }
Here's our main.rs file:
// env_logger_demo/src/main.rs
use log::debug;
use user_auth::User;
fn main() {
env_logger::init();
debug!("env logger demo started");
let user = User::new("bob", "super_sekret");
user.sign_in("super_secret");
user.sign_in("super_sekret");
}
We create our User instance and call sign_in, passing in our password. The first sign in attempt is a failed one, which will get logged as an error. We can run it by setting the RUST_LOG environment variable, followed by cargo run:
RUST_LOG=user_auth=info,env_logger_demo=info cargo run
We set the logs from the user_auth crate to info and the levels above it, while logs from our env_logger_demo crate are set to debug and above.
Running this gives us the following output:
The RUST_LOG accepts the RUST_LOG=path::to_module=log_level[,] pattern, where path::to_module specifies the logger and should be a path to any module with the crate name as the base. The log_level is any of the log levels that are defined in the log crate. [,] at the end indicates that we can optionally have as many of these logger specifications separated by a comma.
An alternative way to run the preceding program is by setting the environment variable within the code itself using the set_var method from the env module in the standard library:
std::env::set_var("RUST_LOG", "user_auth=info,env_logger_demo=info cargo run");
env_logger::init();
This produces the same output as before. Next, let's take a look at a more complex and highly configurable logging crate.