util/cli: refactoring loading log config & add path for log file

This commit is contained in:
ghassmo
2022-05-31 04:27:42 +03:00
parent 16c3a85e8e
commit 01ac20aab4
8 changed files with 55 additions and 37 deletions

View File

@@ -3,11 +3,9 @@ use std::str::FromStr;
use async_executor::Executor;
use async_std::sync::{Arc, Mutex};
use async_trait::async_trait;
use easy_parallel::Parallel;
use futures_lite::future;
use log::{debug, error, info};
use serde_derive::Deserialize;
use simplelog::{ColorChoice, TermLogger, TerminalMode};
use structopt::StructOpt;
use structopt_toml::StructOptToml;
use url::Url;
@@ -36,7 +34,7 @@ use darkfi::{
server::{listen_and_serve, RequestHandler},
},
util::{
cli::{log_config, spawn_config},
cli::{get_log_config, get_log_level, spawn_config},
expand_path,
path::get_config_path,
time::check_clock,

View File

@@ -19,7 +19,7 @@ use darkfi::{
rpc::{client::RpcClient, jsonrpc::JsonRequest},
util::{
async_util,
cli::{log_config, spawn_config, Config},
cli::{get_log_config, get_log_level, spawn_config, Config},
join_config_path, NanoTimestamp,
},
};
@@ -68,11 +68,12 @@ async fn main() -> DnetViewResult<()> {
let verbosity_level = options.app.occurrences_of("verbose");
let (lvl, cfg) = log_config(verbosity_level)?;
let log_level = get_log_level(verbosity_level);
let log_config = get_log_config();
let file = File::create(&*options.log_path).unwrap();
WriteLogger::init(lvl, cfg, file)?;
info!("Log level: {}", lvl);
WriteLogger::init(log_level, log_config, file)?;
info!("Log level: {}", log_level);
let config_path = join_config_path(&PathBuf::from("dnetview_config.toml"))?;

View File

@@ -10,7 +10,10 @@ use darkfi::{
cli_desc,
crypto::address::Address,
rpc::{client::RpcClient, jsonrpc::JsonRequest},
util::{cli::log_config, NetworkName},
util::{
cli::{get_log_config, get_log_level},
NetworkName,
},
Result,
};
@@ -180,8 +183,9 @@ impl Drk {
async fn main() -> Result<()> {
let args = Args::parse();
let (lvl, conf) = log_config(args.verbose.into())?;
TermLogger::init(lvl, conf, TerminalMode::Mixed, ColorChoice::Auto)?;
let log_level = get_log_level(args.verbose.into());
let log_config = get_log_config();
TermLogger::init(log_level, log_config, TerminalMode::Mixed, ColorChoice::Auto)?;
let rpc_client = RpcClient::new(args.endpoint).await?;
let drk = Drk { rpc_client };

View File

@@ -4,13 +4,11 @@ use async_executor::Executor;
use async_std::sync::{Arc, Mutex};
use async_trait::async_trait;
use chrono::Utc;
use easy_parallel::Parallel;
use futures_lite::future;
use log::{debug, error, info};
use num_bigint::BigUint;
use serde_derive::Deserialize;
use serde_json::{json, Value};
use simplelog::{ColorChoice, TermLogger, TerminalMode};
use structopt::StructOpt;
use structopt_toml::StructOptToml;
use url::Url;
@@ -35,7 +33,7 @@ use darkfi::{
server::{listen_and_serve, RequestHandler},
},
util::{
cli::{log_config, spawn_config},
cli::{get_log_config, get_log_level, spawn_config},
decode_base10, expand_path,
path::get_config_path,
serial::serialize,

View File

@@ -6,12 +6,10 @@ use async_std::{
net::{TcpListener, TcpStream},
sync::{Arc, Mutex},
};
use easy_parallel::Parallel;
use futures::{io::BufReader, AsyncBufReadExt, AsyncReadExt, FutureExt};
use fxhash::FxHashMap;
use log::{debug, error, info, warn};
use rand::rngs::OsRng;
use simplelog::{ColorChoice, TermLogger, TerminalMode};
use smol::future;
use structopt_toml::StructOptToml;
use url::Url;
@@ -21,7 +19,7 @@ use darkfi::{
raft::{NetMsg, ProtocolRaft, Raft},
rpc::server::listen_and_serve,
util::{
cli::{log_config, spawn_config},
cli::{get_log_config, get_log_level, spawn_config},
path::{expand_path, get_config_path},
},
Error, Result,

View File

@@ -5,7 +5,11 @@ use log::error;
use simplelog::{ColorChoice, TermLogger, TerminalMode};
use url::Url;
use darkfi::{rpc::client::RpcClient, util::cli::log_config, Error, Result};
use darkfi::{
rpc::client::RpcClient,
util::cli::{get_log_config, get_log_level},
Error, Result,
};
mod filter;
mod primitives;
@@ -76,8 +80,9 @@ pub struct Tau {
async fn main() -> Result<()> {
let args = Args::parse();
let (lvl, conf) = log_config(args.verbose.into())?;
TermLogger::init(lvl, conf, TerminalMode::Mixed, ColorChoice::Auto)?;
let log_level = get_log_level(args.verbose.into());
let log_config = get_log_config();
TermLogger::init(log_level, log_config, TerminalMode::Mixed, ColorChoice::Auto)?;
let rpc_client = RpcClient::new(args.endpoint).await?;
let tau = Tau { rpc_client };

View File

@@ -3,10 +3,8 @@ use std::{env, fs::create_dir_all};
use async_executor::Executor;
use crypto_box::{aead::Aead, Box, SecretKey, KEY_SIZE};
use easy_parallel::Parallel;
use futures::{select, FutureExt};
use log::{debug, error, info, warn};
use simplelog::{ColorChoice, TermLogger, TerminalMode};
use smol::future;
use structopt_toml::StructOptToml;
use url::Url;
@@ -16,7 +14,7 @@ use darkfi::{
raft::{NetMsg, ProtocolRaft, Raft},
rpc::server::listen_and_serve,
util::{
cli::{log_config, spawn_config},
cli::{get_log_config, get_log_level, spawn_config},
expand_path,
path::get_config_path,
serial::{deserialize, serialize, SerialDecodable, SerialEncodable},

View File

@@ -51,14 +51,16 @@ pub fn spawn_config(path: &Path, contents: &[u8]) -> Result<()> {
Ok(())
}
pub fn log_config(verbosity_level: u64) -> Result<(simplelog::LevelFilter, simplelog::Config)> {
let log_level = match verbosity_level {
pub fn get_log_level(verbosity_level: u64) -> simplelog::LevelFilter {
match verbosity_level {
0 => simplelog::LevelFilter::Info,
1 => simplelog::LevelFilter::Debug,
_ => simplelog::LevelFilter::Trace,
};
}
}
let log_config = match env::var("LOG_TARGETS") {
pub fn get_log_config() -> simplelog::Config {
match env::var("LOG_TARGETS") {
Ok(x) => {
let targets: Vec<String> = x.split(',').map(|x| x.to_string()).collect();
let mut cfgbuilder = ConfigBuilder::new();
@@ -74,9 +76,7 @@ pub fn log_config(verbosity_level: u64) -> Result<(simplelog::LevelFilter, simpl
cfgbuilder.build()
}
Err(_) => simplelog::Config::default(),
};
Ok((log_level, log_config))
}
}
pub const ANSI_LOGO: &str = include_str!("../../contrib/darkfi.ansi");
@@ -115,17 +115,14 @@ macro_rules! cli_desc {
///
/// Example usage:
/// ```text
/// use async_executor::Executor;
/// use async_std::sync::Arc;
/// use easy_parallel::Parallel;
/// use futures_lite::future;
/// use simplelog::{ColorChoice, TermLogger, TerminalMode};
/// use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
///
/// use darkfi::{
/// async_daemonize, cli_desc,
/// util::{
/// cli::{log_config, spawn_config},
/// cli::{get_log_config, get_log_level, spawn_config},
/// path::get_config_path,
/// },
/// Result,
@@ -162,13 +159,32 @@ macro_rules! async_daemonize {
spawn_config(&cfg_path, CONFIG_FILE_CONTENTS.as_bytes())?;
let args = Args::from_args_with_toml(&std::fs::read_to_string(cfg_path)?).unwrap();
let (lvl, conf) = log_config(args.verbose.into())?;
TermLogger::init(lvl, conf, TerminalMode::Mixed, ColorChoice::Auto)?;
let log_level = get_log_level(args.verbose.into());
let log_config = get_log_config();
let env_log_file_path = match std::env::var("DARKFI_LOG") {
Ok(p) => std::fs::File::create(p).unwrap(),
Err(_) => std::fs::File::create("/tmp/darkfi.log").unwrap(),
};
simplelog::CombinedLogger::init(vec![
simplelog::TermLogger::new(
log_level,
log_config.clone(),
simplelog::TerminalMode::Mixed,
simplelog::ColorChoice::Auto,
),
simplelog::WriteLogger::new(
simplelog::LevelFilter::Debug,
simplelog::Config::default(),
env_log_file_path,
),
])?;
// https://docs.rs/smol/latest/smol/struct.Executor.html#examples
let ex = Arc::new(Executor::new());
let ex = Arc::new(async_executor::Executor::new());
let (signal, shutdown) = async_channel::unbounded::<()>();
let (_, result) = Parallel::new()
let (_, result) = easy_parallel::Parallel::new()
// Run four executor threads
.each(0..4, |_| future::block_on(ex.run(shutdown.recv())))
// Run the main future on the current thread.