rust 终端输出 debug 信息
配置方法
- 将
env_logger
log
添加到 Cargo.toml :
打开 Cargo.toml 文件并在 [dependencies] 部分下添加env_logger
log
。
[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 文件中。
use env_logger; use log::debug;
- 如果终端没有输出,可能是日志级别配置的问题。默认情况下,
env_logger
可能不显示调试级别日志。需要设置适当的环境变量来配置日志级别。
在 Linux 和 macOS 上:
export RUST_LOG=debug
在 Windows 上(命令提示符):
set RUST_LOG=debug
在 Windows 上(PowerShell):
$env:RUST_LOG="debug"
完整示例
[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"
log = "0.4"
env_logger = "0.10"
#[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);
}
输出
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]