rustlogging

How to log source file and line numbers with env-logger?


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?


Solution

  • 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