Rust日志追踪库tracing-gum-proc-macro的使用,proc-macro宏增强tracing框架的日志记录功能

以下是使用tracing-gum-proc-macro的完整示例:

首先在Cargo.toml中添加依赖:

tracing-gum-proc-macro = "5.0.0"
tracing = "0.1"

然后是一个完整的使用示例:

use tracing_gum_proc_macro::gum;

#[gum::trace]  // 使用proc-macro增强的trace宏
fn process_data(input: &str) -> Result<String, String> {
    if input.is_empty() {
        return Err("Empty input".to_string());
    }
    
    // 自动记录函数参数和返回值
    Ok(input.to_uppercase())
}

#[gum::debug]  // 使用proc-macro增强的debug宏
fn validate_input(input: &str) -> bool {
    // 自动记录函数调用和返回
    input.len() > 5
}

fn main() {
    // 初始化tracing订阅器
    tracing_subscriber::fmt().init();

    let input = "test input";
    
    if validate_input(input) {
        match process_data(input) {
            Ok(output) => {
                // 使用gum宏记录结构化日志
                gum::info!("Processing completed", output);
            }
            Err(e) => {
                gum::error!("Processing failed", error: e);
            }
        }
    } else {
        gum::warn!("Invalid input length", input_length: input.len());
    }
}

这个示例展示了:

  1. 使用#[gum::trace]#[gum::debug]属性宏自动记录函数调用和返回值
  2. 使用结构化的日志记录宏如gum::info!gum::error!gum::warn!
  3. 自动捕获和记录函数参数
  4. 与标准tracing框架的集成

tracing-gum-proc-macro通过过程宏增强了tracing框架的功能,提供了更简洁的API和自动化的日志记录能力。

以下是一个更完整的示例代码,展示了更多tracing-gum-proc-macro的功能:

use tracing_gum_proc_macro::gum;

// 带参数和返回值的函数,使用trace宏自动记录
#[gum::trace]
fn calculate(a: i32, b: i32) -> i32 {
    a + b
}

// 使用debug宏记录函数调用
#[gum::debug]
fn should_process(name: &str) -> bool {
    !name.is_empty()
}

// 使用info宏记录结构化日志
fn log_operation(name: &str, value: i32) {
    gum::info!(
        operation = "log",
        name,
        value,
        "Logging operation completed"
    );
}

fn main() {
    // 初始化tracing订阅器
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::TRACE)
        .init();

    let result = calculate(5, 3);
    gum::debug!("Calculation result", result);

    let name = "example";
    if should_process(name) {
        log_operation(name, result);
    } else {
        gum::warn!("Empty name provided", name);
    }

    // 错误处理示例
    match process_data("") {
        Ok(_) => gum::info!("Process succeeded"),
        Err(e) => gum::error!("Process failed", error: e),
    }
}

1 回复

Rust日志追踪库tracing-gum-proc-macro使用指南

tracing-gum-proc-macro是一个基于Rust tracing框架的过程宏扩展库,它提供了更简洁的语法来记录结构化的日志信息。

主要特性

  1. 简化tracing宏的使用语法
  2. 自动捕获函数参数作为日志字段
  3. 提供更直观的日志格式化方式
  4. 保持与标准tracing生态的兼容性

完整示例demo

use tracing_gum_proc_macro::gum;
use tracing_subscriber;

// 基本示例
#[gum]
fn process_data(data: &str, count: usize) {
    tracing::info!("Processing data"); // 手动添加日志信息
    println!("Processing: {}, count: {}", data, count);
}

// 自定义日志级别
#[gum(level = "debug")]
fn debug_operation(value: i32) {
    println!("Debug value: {}", value);
}

// 添加额外字段
#[gum(fields(user_id = "123", action = "login"))]
fn user_login(username: &str) {
    println!("User {} logged in", username);
}

// 条件日志记录
#[gum(skip)]
fn secret_operation() {
    println!("This won't be logged");
}

#[gum(only = "data,count")]
fn filtered_logging(data: &str, count: usize, secret: &str) {
    println!("Data: {}, Count: {}, Secret: [REDACTED]", data, count);
}

// 异步函数支持
#[gum]
async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {
    let response = reqwest::get(url).await?;
    response.text().await
}

// 自定义日志消息
#[gum(msg = "Starting processing with {data} and {count} items")]
fn custom_log_message(data: &str, count: usize) {
    println!("Processing with {} and {} items", data, count);
}

// 错误处理日志
#[gum]
fn fallible_operation(success: bool) -> Result<(), String> {
    if success {
        Ok(())
    } else {
        Err("Operation failed".to_string())
    }
}

// 与标准tracing配合使用
#[gum]
fn main_operation() {
    tracing::debug!("Detailed debug information");
    sub_operation();
}

#[gum(level = "info")]
fn sub_operation() {
    println!("Performing sub-operation");
}

#[tokio::main]
async fn main() {
    // 初始化日志订阅者
    tracing_subscriber::fmt().init();

    // 调用各种示例函数
    process_data("test", 10);
    debug_operation(42);
    user_login("admin");
    secret_operation();
    filtered_logging("info", 5, "password123");
    
    let _ = fetch_data("https://example.com").await;
    
    custom_log_message("sample", 3);
    let _ = fallible_operation(false);
    
    main_operation();
}

使用说明

  1. 首先确保在Cargo.toml中添加了必要的依赖:
[dependencies]
tracing = "0.1"
tracing-gum-proc-macro = "0.1"
tracing-subscriber = "0.3"
tokio = { version = "1.0", features = ["full"] }
reqwest = "0.11"
  1. 这个完整示例展示了tracing-gum-proc-macro的大多数功能:

    • 基本函数日志记录
    • 自定义日志级别
    • 添加额外字段
    • 条件日志记录
    • 异步函数支持
    • 自定义日志消息
    • 错误处理日志
    • 与标准tracing宏混合使用
  2. 运行程序后,你将看到结构化的日志输出,包含函数调用的参数和自定义的日志消息。

性能建议

  1. 对性能敏感的代码路径考虑使用#[gum(skip)]
  2. 在生产环境中适当调整日志级别
  3. 使用tracing的过滤功能控制日志输出量
回到顶部