You need to enable JavaScript to run this app. Rust slog 2.7 如何在日志中打印语句对应的源文件名与行号
优惠活动
大模型
产品
解决方案
定价
更多

Rust slog 2.7 如何在日志中打印语句对应的源文件名与行号

slog 2.7打印日志源码位置解决方案

slog 2.7版本原生支持获取日志触发点的源码位置信息,你使用的slog_term::FullFormat格式化器已经内置了对应打印开关,只需要简单修改配置即可实现需求:

修改方法

所有创建slog_term::FullFormat实例的位置,在调用build()方法前添加.use_file_location(true)配置,即可自动输出日志对应的文件路径和行号。

修改后的完整配置代码

pub fn configure_log(log_file_name: &str) -> slog::Logger {
    println!(
        "'{}' at configure_log(), log_file_name is:'{}'",
        chrono::prelude::Utc::now(),
        log_file_name
    );
    let log_file_path = std::path::Path::new(log_file_name);
    let dir_file_path = log_file_path.parent().unwrap();
    std::fs::create_dir_all(dir_file_path).unwrap();

    let log_file_handler_option = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(log_file_name)
        ;
    let log_file_handler = match log_file_handler_option {
        Ok(f) => f,
        Err(e) => {
            println!("{}", e);
            panic!();
        }
    };

    let decorator = slog_term::TermDecorator::new().build();
    // 第一个FullFormat开启位置打印
    let my_log_drain = slog_term::FullFormat::new(decorator).use_file_location(true).build().fuse();
    let my_log_drain = slog_envlogger::new(my_log_drain);
    let my_log_drain = slog_async::Async::new(
        slog::Duplicate::new(
            slog::Filter::new(
                // 日志文件输出的FullFormat开启位置打印
                slog_term::FullFormat::new(slog_term::PlainSyncDecorator::new(log_file_handler))
                    .use_file_location(true)
                    .build(),
                |record: &slog::Record| record.level().is_at_least(slog::Level::Warning),
            ),
            slog::Duplicate::new(
                slog::Filter::new(
                    // stderr输出的FullFormat开启位置打印
                    slog_term::FullFormat::new(slog_term::PlainSyncDecorator::new(
                        std::io::stderr(),
                    ))
                    .use_file_location(true)
                    .build(),
                    |record: &slog::Record| record.level().is_at_least(slog::Level::Warning),
                ),
                // 终端标准输出的FullFormat开启位置打印
                slog_term::FullFormat::new(slog_term::TermDecorator::new().build())
                    .use_file_location(true)
                    .build(),
            ),
        )
        .fuse(),
    )
    .build()
    .fuse();

    slog::Logger::root(
        my_log_drain,
        slog::o!("n" => env!("CARGO_PKG_NAME"),"v" => env!("CARGO_PKG_VERSION")),
    )
}

效果说明

配置完成后,所有输出的日志末尾会自动带上文件路径:行号的标识,你也可以通过自定义格式化逻辑调整位置信息的显示样式,比如只显示文件名而非完整路径、额外显示模块名等。

内容的提问来源于stack exchange,提问作者Allan K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 04:09:03