env_logger

A logging implementation for log which is configured via an environment variable.

大多数应用都需要日志通过控制台来输出当前程序运行的状态信息,在Rust中,常用的为env_logger,配合着标准库中log包来使用。可以说env_logger把log的功能扩展了,所以在log使用前需要将 env_logger加载到内存中

1. 安装

创建项目后添加依赖

如下两种方式添加至项目

1. Cargo.toml

1
2
3
[dependencies]
log = "0.4.0"
env_logger = "0.9.0"

2. Terminal

1
cargo add log env_logger

2. 使用

1. 基础使用

文档[^1]例子如下

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

env_logger::init();

debug!("this is a debug {}", "message");
error!("this is printed by default");

if log_enabled!(Level::Info) {
let x = 3 * 4; // expensive computation
info!("the answer was: {}", x);
}

运行结果:

ShotScreen 2023-10-03 at 13.30.39@2x

只是输出了ERROR级别的log,那么如何输出debug或者info?

类似其他语言一直,日志登记默认为Error

而env_logger通过环境变量RUST_LOG控制日志等级输出

当更改环境变量是,执行结果如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
RUST_LOG=error cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.18s
Running `target/debug/mylog`
[2023-10-03T05:34:28Z ERROR mylog] this is printed by default

do it:
RUST_LOG=debug cargo run

output:
Finished dev [unoptimized + debuginfo] target(s) in 0.03s
Running `target/debug/mylog`
[2023-10-03T05:34:43Z DEBUG mylog] this is a debug message
[2023-10-03T05:34:43Z ERROR mylog] this is printed by default
[2023-10-03T05:34:43Z INFO mylog] the answer was: 12

2. 控制输出等级

Log levels are controlled on a per-module basis, and by default all logging is disabled except for the error level.

日志等级是按照每个模块控制的,默认情况下所有的日志被禁止除了error等级的输出

在模块中控制日志等级,使用env_logger::build创建log的实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mod mylog;

use log::{debug, error, info, log_enabled, Level, LevelFilter};

fn main() {
env_logger::builder()
.filter_level(LevelFilter::Debug)
.init();

debug!("this is a debug {}", "message");
error!("this is printed by default");

if log_enabled!(Level::Info) {
let x = 3 * 4; // expensive computation
info!("the answer was: {}", x);
}
}

将日志输出等级设置为Debug,那么在Debug之上的等级会全部输出在console中

1
2
3
4
5
6
7
➜  log git:(master) ✗ cargo run
Compiling mylog v0.1.0 (/Users/yother/WorkSpace/BackEnd/Rust/log)
Finished dev [unoptimized + debuginfo] target(s) in 1.19s
Running `target/debug/mylog`
[2023-10-03T05:48:46Z DEBUG mylog] this is a debug message
[2023-10-03T05:48:46Z ERROR mylog] this is printed by default
[2023-10-03T05:48:46Z INFO mylog] the answer was: 12

使用build可以自定义日志输出格式,例如颜色,时间戳,输出日之所在位置等

3. 自定义输出格式

env_logger::build

3. 引用

[^1]: crates env_logger addr:https://crates.io/crates/env_logger
[^2]: env_logger doc: https://docs.rs/env_logger/0.10.0/env_logger