feat: setting up log switching for the commands

This commit is contained in:
D. Moonfire 2024-03-09 13:28:54 -06:00
parent 5e095c9627
commit d6c56b3bea
2 changed files with 25 additions and 11 deletions

View file

@ -1,5 +1,6 @@
use anyhow::Result;
use clap::{Parser, Subcommand};
use slog::{o, Drain, Level};
mod get;
@ -11,6 +12,9 @@ mod get;
pub struct RootCommand {
#[command(subcommand)]
command: RootSubcommands,
#[arg(short, long, action = clap::ArgAction::Count, global = true)]
verbose: u8,
}
#[derive(Debug, Subcommand)]
@ -20,7 +24,25 @@ pub enum RootSubcommands {
}
impl RootCommand {
pub async fn run(&self, log: slog::Logger) -> Result<()> {
pub async fn run(&self) -> Result<()> {
// Adjust the verbosity.
let log_level = match self.verbose {
0 => Level::Warning,
1 => Level::Info,
2 => Level::Debug,
_ => Level::Trace,
};
// Set up logging.
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = std::sync::Mutex::new(drain).filter_level(log_level).fuse();
let log = slog::Logger::root(drain, o!());
// Set it up so other libraries can use it without passing log around.
let _log_guard = slog_stdlog::init().unwrap();
// Pass the command in.
match &self.command {
RootSubcommands::Get(cmd) => cmd.run(log).await?,
};

View file

@ -4,7 +4,6 @@
use anyhow::Result;
use clap::Parser;
use slog::{o, Drain};
mod commands;
@ -22,17 +21,10 @@ async fn main() {
}
async fn run() -> Result<i32> {
// Set up logging.
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = std::sync::Mutex::new(drain).fuse();
let log = slog::Logger::root(drain, o!());
let _log_guard = slog_stdlog::init().unwrap();
// Parse the command and process everything.
let args = commands::RootCommand::parse();
args.run(log).await?;
args.run().await?;
Ok(0)
}