How to Log in Rust

Using log Module

Log module does not show any log without a logging implementation[^1].

1
2
3
4
5
6
7
8
9
use log::{debug, trace, info, warn, error};

fn main() {
debug!("debug");
trace!("trace");
info!("info");
warn!("warn");
error!("error");
}

Using env_logger

The env_logger module is a logging implementation we can choose. But even if we init it. The output is not shown as expected.

1
2
3
4
5
6
7
8
9
10
11
use log::{debug, trace, info, warn, error};

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

debug!("debug");
trace!("trace");
info!("info");
warn!("warn");
error!("error");
}

The output only contains error message, because the default logging level is error.

1
[2020-06-17T09:56:01Z ERROR playground] error

The document has explained.

Log levels are controlled on a per-module basis, and by default all logging is disabled except for error!. Logging is controlled via the RUST_LOG environment variable.

Specifying Logging Level

If we want to set the logging level, the environment variable RUST_LOG is required. Such as below.

1
RUST_LOG=info cargo run

Setting Default Logging Level

But we can also change the default logging level explicitly.

1
2
3
4
5
6
7
8
9
10
11
12
use log::{debug, trace, info, warn, error};
use env_logger::Env;

fn main() {
env_logger::from_env(Env::default().default_filter_or("warn")).init();

debug!("debug");
trace!("trace");
info!("info");
warn!("warn");
error!("error");
}

Now you can see all logs higher than specific level.

1
2
[2020-06-17T10:33:10Z WARN  playground] warn
[2020-06-17T10:33:10Z ERROR playground] error

References


[^1]: All avaliable implementations are listed here.