Rust supports a logging facade, which we can include using the following dependency in Cargo.toml
[dependencies] log = "0.4.28"
Now in our main.rs we can use the various levels of logging like this
use log::{info, warn, error, trace, debug, LevelFilter};
fn main() {
debug!("Debug log message");
trace!("Trace log message");
info!("Info log message");
warn!("Warning log message");
error!("Error log message");
}
If you run this, nothing will be output because we need to add a logging provider.
One simple provider is env_logger which will log to standard out. To include, add the following to the Cargo.toml dependencies
env_logger = "0.11.8"
We’ll need to add the use clause
use env_logger::{Builder, Env};
and then we need to initialise the env_logger, we can use the following at the start of the main function
env_logger::init();
This will only output ERROR messages, we can change the log level using the environment variable like this
RUST_LOG=trace
Alternatively we can set the environment variable within code by replace the environment variable and the env_logger::init(); line with
let env = Env::default().filter_or("RUST_LOG", "trace");
Builder::from_env(env).init();
or we can set in code instead using
Builder::new() .filter_level(LevelFilter::Trace) .init();