likko-liu's blog

一些个人经验、感悟、心得,愿共勉

0%

rust终端输出debug信息

0. 配置方法

  • 将 env_logger log 添加到 Cargo.toml :
    打开 Cargo.toml 文件并在 [dependencies] 部分下添加 env_logger log 。
1
2
3
4
5
6
7
8
[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"

[dependencies]
log = "0.4"
env_logger = "0.10"
  • 导入 env_logger log crate:
    确保将 env_logger log crate导入到 main.rs 或 lib.rs 文件中。

    1
    2
    use env_logger;
    use log::debug;
  • 如果终端没有输出,可能是日志级别配置的问题。默认情况下, env_logger 可能不显示调试级别日志。需要设置适当的环境变量来配置日志级别。
    在 Linux 和 macOS 上:

    1
    export RUST_LOG=debug

    在 Windows 上(命令提示符):

    1
    set RUST_LOG=debug

    在 Windows 上(PowerShell):

    1
    $env:RUST_LOG="debug"

1. 完整示例

1
2
3
4
5
6
7
8
9
[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8.5"
log = "0.4"
env_logger = "0.10"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#[warn(unused_imports)]
use log::{debug, error, log_enabled, info, Level};
use env_logger;

fn process_serial_data(n: usize, serial_buf: &[u8]) {
// Log the number of bytes received and the data in hexadecimal format
debug!("rx: {}, {:02X?}", n, &serial_buf[..n]);

// Other processing logic...
}

fn main() {
// Initialize the logger
env_logger::init();

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

// Example data
let n = 4;
let serial_buf = vec![0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01];

// Process the data
process_serial_data(n, &serial_buf);
}

2. 输出

1
2
3
4
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
Running `target/debug/helloworld`
[2024-06-26T01:29:31Z DEBUG helloworld] this is a debug message
[2024-06-26T01:29:31Z DEBUG helloworld] rx: 4, [DE, AD, BE, EF]