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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With