Logging efficiently in Rust

Logging is one of the most important parts of many applications and it's good to know that Rust has us covered in this regard. The default go-to crate should be the log crate, which provides us with useful macros for logging. Then, you can use the backend you want for the loggers, such as the env_logger crate or the log4rs crate.

The log crate gives us some macros, mainly trace!(), debug!()info!(),  warn!(), and error!(), in ascending order of relevance, which we can use to log events that happen in our application. It provides some more boilerplate, but that is basically it, you will now have to configure how those macros behave. For that, you have the actual implementations.

If you want an easy to use, common logger, you should go for env_logger. It has a small footprint and can be configured with environment variables. If you need extra configuration for things such as multiple outputs, both console and files, and extra configuration, you should go for an alternative such as log4rs. Let's check a small env_logger example to see the power of this logging mechanism. You will need to add log and env_logger to your Cargo.toml file:

#[macro_use]
extern crate log;
extern crate env_logger;

fn main() {
env_logger::init();

trace!("Logging {} small thing(s)", 1);
debug!("Some debug information: {}",
"the answer is 42");
info!("This is an interesting information");
error!("An error happened, do something!");
}

If we run that using cargo run, we will see this output, since errors are shown by default:

But we can run it with a different RUST_LOG environment variable, such as RUST_LOG=trace cargo run. This should show the following:

As you can see, colors denote the importance of the message. Note that running cargo with the RUST_LOG variable will show a lot of extra output, since cargo itself uses env_logger. I recommend you read the full documentation of this crate, since it enables you to change formatters, loggers, and much more besides the default behavior.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.62