Skip to content

Instantly share code, notes, and snippets.

@webern
Last active May 21, 2021 23:07
Show Gist options
  • Save webern/50557920aea274204a0aa1f8a03a10e2 to your computer and use it in GitHub Desktop.
Save webern/50557920aea274204a0aa1f8a03a10e2 to your computer and use it in GitHub Desktop.
Initializing Rust env_logger with the settings that I like
// colored = "2"
// chrono = "0"
// env_logger = "0"
// log = "0"
use colored::*;
use std::io::Write;
fn init_logger(default_level: LevelFilter) {
// extract the value of RUST_LOG if it exists
let env_val = std::env::var(env_logger::DEFAULT_FILTER_ENV)
.ok()
.unwrap_or("".into());
// create a builder from env if RUST_LOG exists, otherwise create a default builder
let mut builder = if env_val.is_empty() {
env_logger::Builder::new()
} else {
env_logger::Builder::from_default_env()
};
// set a default filter unless the user has passed a filter using the RUST_LOG env var
if env_val.is_empty() {
builder.filter(Some(env!("CARGO_CRATE_NAME")), default_level);
}
// if the user has passed RUST_LOG_STYLE, use it, otherwise use our favorite style
if let Some(style_env_value) = std::env::var(env_logger::DEFAULT_WRITE_STYLE_ENV).ok() {
builder.parse_write_style(&style_env_value);
} else {
builder.format(|buf, record| {
let level = format!("[{}]", record.level());
let level = match record.level() {
Level::Error => level.red(),
Level::Warn => level.yellow(),
Level::Info => level.cyan(),
Level::Debug => level.truecolor(100, 100, 100),
Level::Trace => level.truecolor(200, 200, 200),
};
writeln!(
buf,
"{}:{} {} {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
chrono::Local::now().format("%Y-%m-%dT%H:%M:%S"),
level,
record.args(),
)
});
}
builder.init()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment