Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log source file and line numbers

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?

like image 505
Matt Joiner Avatar asked May 15 '20 02:05

Matt Joiner


People also ask

What does logging getLogger (__ name __) do?

getLogger(__name__) in multiple modules. Bookmark this question. Show activity on this post. This means that logger names track the package/module hierarchy, and it's intuitively obvious where events are logged just from the logger name.


1 Answers

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

like image 192
Matthew James Briggs Avatar answered Oct 18 '22 03:10

Matthew James Briggs