Reputation: 118470
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?
Upvotes: 13
Views: 5425
Reputation: 2265
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
Upvotes: 20
Reputation: 42197
log::Record has file
and line
methods. You have to check the configuration of env_logger to see if there's built-in support for these, otherwise you might have to configure a custom formatter and hand-roll it.
Upvotes: 0