Rust日志库tklog-如何给日志添加新属性,如线程ID


tklog支持给日志设置独立的格式化功能,即可以支持开发者根据需求给日志添加不同的属性,如线程ID等,

Rust日志库tklog0.2.8—增加控制台日志独立格式化功能


以下是给tklog添加打印线程ID的示例

比如,给 trace 级别的日志打印添加打印线程ID的需求:

解决方法:通过 set_level_fmt 或  set_body_fmt 等地方,加入 线程ID都可以。

以下示例通过 set_level_fmt 添加线程ID



#[test]
fn testlog3() {
    LOG.set_console(true).set_level(LEVEL::Trace).set_attr_format(|fmt| {
        fmt.set_level_fmt(|level| {
            let thread_tag = format!("[trace][{:?}]", thread::current().id());   //修改trace级别的格式,添加一个线程ID进去
            match level {
                LEVEL::Trace => &thread_tag,
                LEVEL::Debug => "[Debug]",
                LEVEL::Info => "[Info]",
                LEVEL::Warn => "[Warn]",
                LEVEL::Error => "[Error]",
                LEVEL::Fatal => "[Fatal]",
                LEVEL::Off => "",
            }
            .to_string()
        });
    });
    LOG.uselog();
    log::trace!("trace!{}", "this is sync log"); 
    log::debug!("debug!{}", "this is sync log");
    log::info!("info!{}", "this is sync log");
    log::warn!("warn!{}", "this is sync log");
    log::error!("error!{}", "this is sync log");

    let handle = thread::spawn(|| {
        log::trace!("trace!{}", "this is thread sync log");
    });

    handle.join().unwrap();
    thread::sleep(Duration::from_secs(3))
}

输出:

[trace][ThreadId(2)] 2025-07-29 11:53:19 test.rs 48:trace!this is sync log
[Debug] 2025-07-29 11:53:19 test.rs 49:debug!this is sync log
[Info] 2025-07-29 11:53:19 test.rs 50:info!this is sync log
[Warn] 2025-07-29 11:53:19 test.rs 51:warn!this is sync log
[Error] 2025-07-29 11:53:19 test.rs 52:error!this is sync log
[trace][ThreadId(4)] 2025-07-29 11:53:19 test.rs 55:trace!this is thread sync log

可以看到  trace 级别的日志,后面带上了线程ID的信息