Skip to content

Instantly share code, notes, and snippets.

@qryxip
Last active March 26, 2020 14:27
Show Gist options
  • Select an option

  • Save qryxip/2f44a1f6efb84c153b9ebf5dde32f284 to your computer and use it in GitHub Desktop.

Select an option

Save qryxip/2f44a1f6efb84c153b9ebf5dde32f284 to your computer and use it in GitHub Desktop.
//! This code is licensed under [CC0-1.0](https://creativecommons.org/publicdomain/zero/1.0).
//!
//! ```cargo
//! [package]
//! name = "logger"
//! version = "0.0.0"
//! authors = ["Ryo Yamashita <[email protected]>"]
//! edition = "2018"
//! license = "CC0-1.0"
//! publish = false
//!
//! [dependencies]
//! env_logger = "0.7.1"
//! log = "0.4.8"
//! structopt = "0.3.12"
//! ```
use env_logger::fmt::{Color, WriteStyle};
use log::{error, info, warn, Level, LevelFilter};
use structopt::StructOpt;
use std::io::Write as _;
fn main() {
let Opt { color } = Opt::from_args();
init(color);
info!("Info");
warn!("Warn");
error!("Error");
}
#[derive(StructOpt, Debug)]
struct Opt {
/// Coloring
#[structopt(
long,
value_name("WHEN"),
default_value("auto"),
possible_values(&["auto", "always", "never"]),
parse(from_str = parse_write_style_unwrap)
)]
color: WriteStyle,
}
fn init(color: WriteStyle) {
env_logger::Builder::new()
.format(|buf, record| {
macro_rules! style(($fg:expr, $intense:expr) => ({
let mut style = buf.style();
style.set_color($fg).set_intense($intense);
style
}));
let color = match record.level() {
Level::Error => Color::Red,
Level::Warn => Color::Yellow,
Level::Info => Color::Cyan,
Level::Debug => Color::Green,
Level::Trace => Color::White,
};
let path = record
.module_path()
.map(|p| p.split("::").next().unwrap())
.filter(|&p| p != module_path!().split("::").next().unwrap())
.map(|p| format!(" {}", p))
.unwrap_or_default();
writeln!(
buf,
"{}{}{}{} {}",
style!(Color::Black, true).value('['),
style!(color, false).value(record.level()),
path,
style!(Color::Black, true).value(']'),
record.args(),
)
})
.filter_level(LevelFilter::Info)
.write_style(color)
.init();
}
/// Parses `s` to a `WriteStyle`.
///
/// # Panics
///
/// Panics `s` is not "auto", "always", or "never".
fn parse_write_style_unwrap(s: &str) -> WriteStyle {
match s {
"auto" => WriteStyle::Auto,
"always" => WriteStyle::Always,
"never" => WriteStyle::Never,
_ => panic!(r#"expected "auto", "always", or "never""#),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment