From f441759e6e102bfc64d3d61d183600dd914338fc Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Mon, 25 Nov 2024 19:05:33 -0800 Subject: [PATCH] feat: Implement `From` for tracing and log types 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(); ``` --- examples/log.rs | 4 ++-- examples/tracing.rs | 4 ++-- src/log.rs | 14 +++++++++++++- src/tracing.rs | 14 +++++++++++++- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/examples/log.rs b/examples/log.rs index 689e7ed..c39f55a 100644 --- a/examples/log.rs +++ b/examples/log.rs @@ -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"); diff --git a/examples/tracing.rs b/examples/tracing.rs index a34246e..2033c9b 100644 --- a/examples/tracing.rs +++ b/examples/tracing.rs @@ -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"); diff --git a/src/log.rs b/src/log.rs index 94d87d2..95537b3 100644 --- a/src/log.rs +++ b/src/log.rs @@ -3,7 +3,7 @@ // information. pub use log::{Level, LevelFilter}; -use crate::VerbosityFilter; +use crate::{Verbosity, VerbosityFilter}; impl From for LevelFilter { fn from(filter: VerbosityFilter) -> Self { @@ -57,6 +57,18 @@ impl From> for VerbosityFilter { } } +impl From for LevelFilter { + fn from(v: Verbosity) -> Self { + v.log_level_filter() + } +} + +impl From for Option { + fn from(v: Verbosity) -> Self { + v.log_level() + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/tracing.rs b/src/tracing.rs index 3715f52..6e71c06 100644 --- a/src/tracing.rs +++ b/src/tracing.rs @@ -3,7 +3,7 @@ // more information. pub use tracing_core::{Level, LevelFilter}; -use crate::VerbosityFilter; +use crate::{Verbosity, VerbosityFilter}; impl From for LevelFilter { fn from(filter: VerbosityFilter) -> Self { @@ -57,6 +57,18 @@ impl From> for VerbosityFilter { } } +impl From for LevelFilter { + fn from(v: Verbosity) -> Self { + v.tracing_level_filter() + } +} + +impl From for Option { + fn from(v: Verbosity) -> Self { + v.tracing_level() + } +} + #[cfg(test)] mod tests { use super::*;