Errors - part 2

Previously, we've seen how to create and handle errors in Rust. In this chapter, we'll look at how to log errors.

Using println to print an error to standard output, has no practical use outside an example. If you want to output errors in production code, you should use Rust's logging framework: log.

Include it in the Cargo.toml file:

[dependencies]
log = "0.4"

The log crate does not include an implementation. You need to combine it with a specific implementation in order for it to work.

We use the env_logger logging implementation. It is very easy to use and provides a good starting point for logging in Rust. It reads the RUST_LOG environment variable to set the log level. Possible values are trace, debug, info, warn, and error.

Add the following to your Cargo.toml file:

[dependencies]
log = "0.4"
env_logger = "0.11"

Without re-doing the whole "Error" example again, here's how you can replace the println statement with some logging variants:

use log::*;

fn main() {
    env_logger::init();
    trace!("This line is not printed");
    debug!("Neither is this line");
    info!("Playground initialized...");
    warn!("Failed to retrieve user {} from the database: {}", "bob", "user not found");
    error!("Failed to retrieve user {} from the database: {}", "bob", "I/O error; timeout");
}

Development teams will have their own set of rules on the use of the various log levels. We use these:

  • TRACE: lowest level step-through of the program code.Only practically useful in a test/dev environment due to the large amount of data logged.
  • DEBUG: optional logs to help (developers) identify why a particular situation/error occurred.
  • INFO: (regular) information that is useful for an operation team to monitor proper behaviour of the application.
  • WARN: expected (user) errors, that have no effect on the correct functioning of the application.
  • ERROR: error situations that need an action to get remediated. The application cannot recover from these errors.

In general, make sure to include a unique identifier in all your log statements. You want to be able to grep log output and find all related log-lines easily.

We'll expand on logging in this chapter, where we'll cover how to write meaningful log messages.