rust 終端輸出 debug 資訊

likkoliu發表於2024-06-26

配置方法

  • 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]

相關文章