From fc181409161612a41499bdf3d19bda6913161ffc Mon Sep 17 00:00:00 2001 From: lemonsh Date: Sun, 17 Jul 2022 21:39:09 +0200 Subject: [PATCH] Log level in config instead of environment --- Cargo.toml | 2 +- sample_uberbot.toml | 2 ++ src/config.rs | 1 + src/main.rs | 30 +++++++++++++++++------------- 4 files changed, 21 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5df4673..04a5e4d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ lto = true tokio = { version = "1", features = ["rt-multi-thread", "macros", "signal"] } anyhow = "1.0" tracing = "0.1" -tracing-subscriber = { version = "0.3", features = ["env-filter"] } +tracing-subscriber = "0.3" reqwest = { version = "0.11", default-features = false, features = ["rustls-tls"] } serde_json = "1.0" fancy-regex = "0.10" diff --git a/sample_uberbot.toml b/sample_uberbot.toml index 011cce9..6899f28 100644 --- a/sample_uberbot.toml +++ b/sample_uberbot.toml @@ -1,3 +1,5 @@ +log_level = "debug" # optional, default: info + [irc] host = "karx.xyz" port = 6697 diff --git a/src/config.rs b/src/config.rs index 6eb9ca3..b2d052f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,6 +2,7 @@ use serde::Deserialize; #[derive(Deserialize)] pub struct UberConfig { + pub log_level: Option, pub irc: IrcConfig, pub spotify: Option, pub bot: BotConfig diff --git a/src/main.rs b/src/main.rs index 93f5dbb..d7cb283 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,8 @@ #![allow(clippy::module_name_repetitions)] use fancy_regex::Regex; -use std::env; -use std::fs::File; -use std::io::Read; +use std::{env, fs}; +use std::str::FromStr; use std::sync::Arc; use std::thread; @@ -24,7 +23,7 @@ use rspotify::Credentials; use tokio::select; use tokio::sync::broadcast; use tokio::sync::mpsc::unbounded_channel; -use tracing_subscriber::EnvFilter; +use tracing::Level; use crate::config::UberConfig; use crate::database::{DbExecutor, ExecutorConnection}; @@ -57,17 +56,22 @@ async fn terminate_signal() { #[tokio::main] async fn main() -> anyhow::Result<()> { - tracing_subscriber::fmt() - .with_env_filter(EnvFilter::from_env("UBERBOT_LOG")) + let config_var = env::var("UBERBOT_CONFIG"); + let config_path = config_var.as_deref().unwrap_or("uberbot.toml"); + println!("Loading config from '{}'...", config_path); + let config_str = fs::read_to_string(config_path)?; + let cfg: UberConfig = toml::from_str(&config_str)?; + + tracing_subscriber::fmt::fmt() + .with_max_level({ + if let Some(o) = cfg.log_level.as_deref() { + Level::from_str(o)? + } else { + Level::INFO + } + }) .init(); - let mut file = - File::open(env::var("UBERBOT_CONFIG").unwrap_or_else(|_| "uberbot.toml".to_string()))?; - let mut client_conf = String::new(); - file.read_to_string(&mut client_conf)?; - - let cfg: UberConfig = toml::from_str(&client_conf)?; - let (db_exec, db_conn) = DbExecutor::create(cfg.bot.db_path.as_deref().unwrap_or("uberbot.db3"))?; let exec_thread = thread::spawn(move || db_exec.run());