Logging in Rust

Logging in Rust

I need to record the logging from my application. According to this, rust can do logging via the log crate:

use log::{info, warn};

pub fn example() {
  info!("Here's some info");
  warn!("This is a warning!");
}

In addition, you can use the env_logger crate to configure a simple logger like so:

env_logger::init();

This looks if there's an environment variable named RUST_LOG and enables/disables logs based on the level (default is info).

If simple is not enough...

Than you have full-blown logging capabilities via the log4rs crate. It can record the logs on different media (stdout, files, rotating logs) and allows configuration via YAML (along with programmatically). You can even format the logs!

Following the documentation, all you need to do is to create the YAML configuration file and put the following in the application's initialisation code:

log4rs::init_file("log4rs.yml", Default::default()).unwrap();

HTH,