diff options
author | Keuin <[email protected]> | 2022-03-28 00:06:58 +0800 |
---|---|---|
committer | Keuin <[email protected]> | 2022-03-28 00:11:45 +0800 |
commit | b611e395a2d002c0696c2c10e2f43b3f9013c6d9 (patch) | |
tree | 0d1e1ea4ce417022ac556b15330112aa2e7fed04 /src/main.rs | |
parent | ab4b8903ee9b009c3e1a188f1cfe09e39272d2ee (diff) |
Decent logging. Configurable log level.v0.2.0
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 42 |
1 files changed, 31 insertions, 11 deletions
diff --git a/src/main.rs b/src/main.rs index ad5fdf3..f67a6bc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,13 @@ use std::convert::Infallible; use std::net::SocketAddr; +use std::ops::Deref; +use std::str::FromStr; use std::sync::Arc; -use log::{debug, error, info, warn}; use teloxide::prelude2::*; +use tracing::{debug, info, Level}; +use tracing::instrument; +use tracing_subscriber::FmtSubscriber; use warp::Filter; use config::Config; @@ -19,6 +23,7 @@ mod config; const CONFIG_FILE_NAME: &str = "kimikuri.json"; const MAX_BODY_LENGTH: u64 = 1024 * 16; +const DEFAULT_LOG_LEVEL: Level = Level::DEBUG; fn with_db(db_pool: DbPool) -> impl Filter<Extract=(DbPool, ), Error=Infallible> + Clone { warp::any().map(move || db_pool.clone()) @@ -29,13 +34,28 @@ fn with_bot(bot: Bot) -> impl Filter<Extract=(Bot, ), Error=Infallible> + Clone warp::any().map(move || bot.clone()) } +#[instrument] #[tokio::main] async fn main() { - pretty_env_logger::init(); - debug!("Loading bot config."); + eprintln!("Loading configuration file {}...", CONFIG_FILE_NAME); + // TODO make some fields optional let config = Config::from_file(CONFIG_FILE_NAME); - info!("Starting bot."); - let bot = Bot::new(config.bot_token); + + // configure logger + let log_level = match Level::from_str(&*config.log_level) { + Ok(l) => l, + Err(_) => { + eprintln!("Invalid log level: {}. Use {:?} instead.", + config.log_level, DEFAULT_LOG_LEVEL); + DEFAULT_LOG_LEVEL + } + }; + eprintln!("Configuration is loaded. Set log level to {:?}.", log_level); + let subscriber = FmtSubscriber::builder() + .with_max_level(log_level) + .finish(); + tracing::subscriber::set_global_default(subscriber) + .expect("Failed to set default subscriber"); let db = config.db_file.as_str(); info!(db, "Opening database..."); @@ -51,18 +71,18 @@ async fn main() { .and(with_db(db.deref().clone())) .and(with_bot(bot.clone())) .and_then(web::handler); + tokio::spawn(bot::repl(bot, db.clone())); - tokio::spawn(bot::repl(bot, Arc::new(db))); - + info!("Starting HTTP server..."); let endpoint: SocketAddr = config.listen.parse() .expect("Cannot parse `listen` as endpoint."); - - println!("Listen on {}", endpoint); - + info!("Start listening on {}", endpoint); tokio::spawn(warp::serve(send_message).run(endpoint)); + debug!("Waiting for Ctrl-C in main coroutine..."); tokio::signal::ctrl_c().await.unwrap(); - + // gracefully shutdown the database connection + info!("Closing database..."); db.deref().close().await; } |