Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

--quiet and configurable default log level #18

Merged
merged 3 commits into from
Oct 17, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 45 additions & 13 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ use log::Level;
/// # Examples
///
/// ```rust
/// extern crate clap_verbosity_flag;
/// #[macro_use] extern crate structopt;
///
/// use structopt::StructOpt;
/// use clap_verbosity_flag::Verbosity;
///
Expand All @@ -26,27 +23,62 @@ pub struct Verbosity {
///
/// By default, it'll only report errors. Passing `-v` one time also prints
/// warnings, `-vv` enables info logging, `-vvv` debug, and `-vvvv` trace.
#[structopt(long = "verbosity", short = "v", parse(from_occurrences))]
verbosity: u8,
#[structopt(long, short = "v", parse(from_occurrences))]
verbose: i8,

/// Pass many times for less log output
#[structopt(long, short = "q", parse(from_occurrences), conflicts_with = "verbose")]
quiet: i8,

#[structopt(skip)]
default: i8,
}

impl Verbosity {
/// Change the default level.
pub fn set_default(&mut self, level: Level) {
self.default = level_value(level);
}

/// Get the log level.
pub fn log_level(&self) -> Level {
match self.verbosity {
0 => Level::Error,
1 => Level::Warn,
2 => Level::Info,
3 => Level::Debug,
_ => Level::Trace,
}
level_enum(self.verbosity())
}

/// If the user requested complete silence (i.e. not just no-logging).
pub fn is_silent(&self) -> bool {
self.verbosity() < 0
}

fn verbosity(&self) -> i8 {
self.default - self.quiet + self.verbose
}
}

fn level_value(level: Level) -> i8 {
match level {
log::Level::Error => 0,
log::Level::Warn => 1,
log::Level::Info => 2,
log::Level::Debug => 3,
log::Level::Trace => 4,
}
}

fn level_enum(verbosity: i8) -> Level {
match verbosity {
std::i8::MIN..=0 => log::Level::Error,
1 => log::Level::Warn,
2 => log::Level::Info,
3 => log::Level::Debug,
4..=std::i8::MAX => log::Level::Trace,
}
}

use std::fmt;

impl fmt::Display for Verbosity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.verbosity)
write!(f, "{}", self.verbose)
}
}