Skip to content

Commit

Permalink
feat: Implement From<Verbosity> for tracing and log types
Browse files Browse the repository at this point in the history
This makes it possible to just directly setup the log filter:

E.g.:
```rust
env_logger::Builder::new().filter_level(cli.verbosity.into()).init();
// or
tracing_subscriber::fmt().with_max_level(cli.verbosity).init();
```
  • Loading branch information
joshka committed Nov 26, 2024
1 parent 02d8ea5 commit f441759
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 6 deletions.
4 changes: 2 additions & 2 deletions examples/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ use clap_verbosity_flag::Verbosity;
#[derive(Debug, Parser)]
struct Cli {
#[command(flatten)]
verbose: Verbosity,
verbosity: Verbosity,
}

fn main() {
let cli = Cli::parse();

env_logger::Builder::new()
.filter_level(cli.verbose.log_level_filter())
.filter_level(cli.verbosity.into())
.init();

log::error!("Engines exploded");
Expand Down
4 changes: 2 additions & 2 deletions examples/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ use clap_verbosity_flag::Verbosity;
#[derive(Debug, Parser)]
struct Cli {
#[command(flatten)]
verbose: Verbosity,
verbosity: Verbosity,
}

fn main() {
let cli = Cli::parse();

tracing_subscriber::fmt()
.with_max_level(cli.verbose.tracing_level_filter())
.with_max_level(cli.verbosity)
.init();

tracing::error!("Engines exploded");
Expand Down
14 changes: 13 additions & 1 deletion src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// information.
pub use log::{Level, LevelFilter};

use crate::VerbosityFilter;
use crate::{Verbosity, VerbosityFilter};

impl From<VerbosityFilter> for LevelFilter {
fn from(filter: VerbosityFilter) -> Self {
Expand Down Expand Up @@ -57,6 +57,18 @@ impl From<Option<Level>> for VerbosityFilter {
}
}

impl From<Verbosity> for LevelFilter {
fn from(v: Verbosity) -> Self {
v.log_level_filter()
}
}

impl From<Verbosity> for Option<Level> {
fn from(v: Verbosity) -> Self {
v.log_level()
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
14 changes: 13 additions & 1 deletion src/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// more information.
pub use tracing_core::{Level, LevelFilter};

use crate::VerbosityFilter;
use crate::{Verbosity, VerbosityFilter};

impl From<VerbosityFilter> for LevelFilter {
fn from(filter: VerbosityFilter) -> Self {
Expand Down Expand Up @@ -57,6 +57,18 @@ impl From<Option<Level>> for VerbosityFilter {
}
}

impl From<Verbosity> for LevelFilter {
fn from(v: Verbosity) -> Self {
v.tracing_level_filter()
}
}

impl From<Verbosity> for Option<Level> {
fn from(v: Verbosity) -> Self {
v.tracing_level()
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit f441759

Please sign in to comment.