Warm tip: This article is reproduced from serverfault.com, please click

Log source file and line numbers

发布于 2020-05-15 02:31:19

Using Rust's log, and env_logger crates, how do I have the output include the source file and line number where a log call was invoked?

Questioner
Matt Joiner
Viewed
0
Matthew James Briggs 2020-12-01 11:36:31

In the following example logger_example is the name of my binary in Cargo.toml, e.g.

[[bin]]
name = "logger_example"
path = "src/bin/logger_example.rs"

You can custom-format the logger like this:

use log::{info, LevelFilter};
use std::io::Write;

fn main() {
    env_logger::Builder::new()
        .format(|buf, record| {
            writeln!(
                buf,
                "{}:{} {} [{}] - {}",
                record.file().unwrap_or("unknown"),
                record.line().unwrap_or(0),
                chrono::Local::now().format("%Y-%m-%dT%H:%M:%S"),
                record.level(),
                record.args()
            )
        })
        .filter(Some("logger_example"), LevelFilter::Debug)
        .init();

    info!("hello world")
}

The output is:

src/bin/logger_example.rs:20 2020-11-30T19:34:16 [INFO] - hello world

I found the answer here: https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log.html