From a99d9ba7f48ebdff12e4db2028e664240b41b679 Mon Sep 17 00:00:00 2001 From: Einliterflasche Date: Mon, 19 Aug 2024 15:49:14 +0200 Subject: [PATCH] fix: log paths and remove -o flag --- swap/src/api/request.rs | 11 ++--- swap/src/asb/command.rs | 8 ---- swap/src/bin/asb.rs | 26 +++++++----- swap/src/cli/command.rs | 9 +--- swap/src/common/mod.rs | 75 ++++++--------------------------- swap/src/common/tracing_util.rs | 2 +- swap/src/rpc/methods.rs | 19 ++++++++- 7 files changed, 54 insertions(+), 96 deletions(-) diff --git a/swap/src/api/request.rs b/swap/src/api/request.rs index 5655c01a..69b244b1 100644 --- a/swap/src/api/request.rs +++ b/swap/src/api/request.rs @@ -1,7 +1,7 @@ use crate::api::Context; use crate::bitcoin::{Amount, ExpiredTimelocks, TxLock}; use crate::cli::{list_sellers, EventLoop, SellerStatus}; -use crate::common::print_or_write_logs; +use crate::common::get_logs; use crate::libp2p_ext::MultiAddrExt; use crate::network::quote::{BidQuote, ZeroQuoteReceived}; use crate::network::swarm; @@ -49,7 +49,6 @@ pub enum Method { History, Logs { logs_dir: Option, - output_path: Option, redact: bool, swap_id: Option }, @@ -662,10 +661,12 @@ impl Request { Ok(json!({ "swaps": vec })) } - Method::Logs { logs_dir, output_path, redact, swap_id } => { - print_or_write_logs(logs_dir, output_path, swap_id, redact).await?; + Method::Logs { logs_dir, redact, swap_id } => { + let dir = logs_dir.unwrap_or(context.config.data_dir.join("logs")); - Ok(json!({ "success": true })) + let logs = get_logs(dir, swap_id, redact).await?; + + Ok(json!({ "logs": logs })) } Method::GetRawStates => { let raw_history = context.db.raw_all().await?; diff --git a/swap/src/asb/command.rs b/swap/src/asb/command.rs index 867c1355..07bf2ff6 100644 --- a/swap/src/asb/command.rs +++ b/swap/src/asb/command.rs @@ -39,7 +39,6 @@ where cmd: Command::History, }, RawCommand::Logs { - output_path, logs_dir: dir_path, swap_id, redact, @@ -50,7 +49,6 @@ where env_config: env_config(testnet), cmd: Command::Logs { logs_dir: dir_path, - output_path, swap_id, redact, }, @@ -203,7 +201,6 @@ pub enum Command { Config, Logs { logs_dir: Option, - output_path: Option, swap_id: Option, redact: bool, }, @@ -287,11 +284,6 @@ pub enum RawCommand { help = "Print the logs from this directory instead of the default one." )] logs_dir: Option, - #[structopt( - short = "o", - help = "Print the logs into this file instead of the terminal." - )] - output_path: Option, #[structopt( help = "Redact swap-ids, Bitcoin and Monero addresses.", long = "redact" diff --git a/swap/src/bin/asb.rs b/swap/src/bin/asb.rs index 3de587d5..44d848b5 100644 --- a/swap/src/bin/asb.rs +++ b/swap/src/bin/asb.rs @@ -30,9 +30,8 @@ use swap::asb::config::{ initial_setup, query_user_for_initial_config, read_config, Config, ConfigNotInitialized, }; use swap::asb::{cancel, punish, redeem, refund, safely_abort, EventLoop, Finality, KrakenRate}; -use swap::common::{self, check_latest_version, print_or_write_logs}; +use swap::common::{self, check_latest_version, get_logs}; use swap::database::{open_db, AccessMode}; -use swap::fs::system_data_dir; use swap::network::rendezvous::XmrBtcNamespace; use swap::network::swarm; use swap::protocol::alice::{run, AliceState}; @@ -69,13 +68,7 @@ async fn main() -> Result<()> { // warn if we're not on the latest version if let Err(e) = check_latest_version(env!("CARGO_PKG_VERSION")).await { eprintln!("{}", e); - } - - // initialize tracing - let format = if json { Format::Json } else { Format::Raw }; - let log_dir = system_data_dir()?.join("logs"); - common::tracing_util::init(LevelFilter::DEBUG, format, log_dir) - .expect("initialize tracing"); + } // read config from the specified path let config = match read_config(config_path.clone())? { @@ -86,6 +79,12 @@ async fn main() -> Result<()> { } }; + // initialize tracing + let format = if json { Format::Json } else { Format::Raw }; + let log_dir = config.data.dir.join("logs"); + common::tracing_util::init(LevelFilter::DEBUG, format, log_dir) + .expect("initialize tracing"); + // check for conflicting env / config values if config.monero.network != env_config.monero_network { bail!(format!( @@ -254,11 +253,16 @@ async fn main() -> Result<()> { } Command::Logs { logs_dir, - output_path, swap_id, redact, } => { - print_or_write_logs(logs_dir, output_path, swap_id, redact).await?; + let dir = logs_dir.unwrap_or(config.data.dir.join("logs")); + + let log_messages = get_logs(dir, swap_id, redact).await?; + + for msg in log_messages { + println!("{msg}"); + } } Command::WithdrawBtc { amount, address } => { let bitcoin_wallet = init_bitcoin_wallet(&config, &seed, env_config).await?; diff --git a/swap/src/cli/command.rs b/swap/src/cli/command.rs index 810f88ef..c0cf9046 100644 --- a/swap/src/cli/command.rs +++ b/swap/src/cli/command.rs @@ -105,13 +105,13 @@ where } CliCommand::Logs { logs_dir, - output_path, redact, swap_id } => { - let request = Request::new(Method::Logs { logs_dir, output_path, redact, swap_id }); + let request = Request::new(Method::Logs { logs_dir, redact, swap_id }); let context = Context::build(None, None, None, data, is_testnet, debug, json, None).await?; + println!("here"); (context, request) } CliCommand::Config => { @@ -339,11 +339,6 @@ enum CliCommand { help = "Print the logs from this directory instead of the default one." )] logs_dir: Option, - #[structopt( - short = "o", - help = "Print the logs into this file instead of the terminal." - )] - output_path: Option, #[structopt( help = "Redact swap-ids, Bitcoin and Monero addresses.", long = "redact" diff --git a/swap/src/common/mod.rs b/swap/src/common/mod.rs index c80e7f38..a1a8f13a 100644 --- a/swap/src/common/mod.rs +++ b/swap/src/common/mod.rs @@ -3,11 +3,9 @@ pub mod tracing_util; use std::{collections::HashMap, path::PathBuf}; use anyhow::anyhow; -use tokio::{fs::{create_dir_all, read_dir, try_exists, File}, io::{self, stdout, AsyncBufReadExt, AsyncWriteExt, BufReader, Stdout}}; +use tokio::{fs::{read_dir, File}, io::{AsyncBufReadExt, BufReader}}; use uuid::Uuid; -use crate::fs::system_data_dir; - const LATEST_RELEASE_URL: &str = "https://github.com/comit-network/xmr-btc-swap/releases/latest"; #[derive(Clone, Debug, PartialEq, Eq)] @@ -51,6 +49,7 @@ macro_rules! regex_find_placeholders { ($pattern:expr, $create_placeholder:expr, $replacements:expr, $input:expr) => {{ // compile the regex pattern static REGEX: once_cell::sync::Lazy = once_cell::sync::Lazy::new(|| { + tracing::debug!("initializing regex"); regex::Regex::new($pattern).expect("invalid regex pattern") }); @@ -72,64 +71,14 @@ macro_rules! regex_find_placeholders { /// to the specified path or the terminal. /// /// If specified, filter by swap id or redact addresses. -pub async fn print_or_write_logs(logs_dir: Option, output_path: Option, swap_id: Option, redact_addresses: bool) -> anyhow::Result<()> { - // use provided directory of default one - let default_dir = system_data_dir()?.join("logs"); - let logs_dir = logs_dir.unwrap_or(default_dir); - - tracing::info!("Reading `*.log` files from `{}`", logs_dir.display()); +pub async fn get_logs(logs_dir: PathBuf, swap_id: Option, redact_addresses: bool) -> anyhow::Result> { + tracing::debug!(logs_dir=%logs_dir.display(), "reading logfiles from"); // get all files in the directory let mut log_files = read_dir(&logs_dir).await?; - /// Enum for abstracting over output channels - enum OutputChannel { - File(File), - Stdout(Stdout), - } + let mut log_messages = Vec::new(); - /// Conveniance method for writing to either file or stdout - async fn write_to_channel( - mut channel: &mut OutputChannel, - output: &str, - ) -> Result<(), io::Error> { - match &mut channel { - OutputChannel::File(file) => file.write_all(output.as_bytes()).await, - OutputChannel::Stdout(stdout) => stdout.write_all(output.as_bytes()).await, - } - } - - // check where we should write to - let mut output_channel = match output_path { - Some(path) => { - // make sure the directory exists - if !try_exists(&path).await? { - let mut dir_part = path.clone(); - dir_part.pop(); - create_dir_all(&dir_part).await?; - } - - tracing::info!("Writing logs to `{}`", path.display()); - - // create/open and truncate file. - // this means we aren't appending which is probably intuitive behaviour - // since we reprint the complete logs anyway - OutputChannel::File(File::create(&path).await?) - } - None => OutputChannel::Stdout(stdout()), - }; - - // conveniance method for checking whether we should filter a specific line - let filter_by_swap_id: Box bool + Send + Sync> = match swap_id { - // if we should filter by swap id, check if the line contains the string - Some(swap_id) => { - let swap_id = swap_id.to_string(); - Box::new(move |line: &str| line.contains(&swap_id)) - } - // otherwise we let every line pass - None => Box::new(|_| true), - }; - // print all lines from every log file. TODO: sort files by date? while let Some(entry) = log_files.next_entry().await? { // get the file path @@ -151,18 +100,20 @@ pub async fn print_or_write_logs(logs_dir: Option, output_path: Option< // print each line, redacted if the flag is set while let Some(line) = lines.next_line().await? { // check if we should filter this line - if !filter_by_swap_id(&line) { - continue; + if let Some(swap_id) = swap_id { + if line.contains(&swap_id.to_string()) { + continue; + } } + // redact if necessary let line = if redact_addresses { redact(&line) } else { line }; - write_to_channel(&mut output_channel, &line).await?; - // don't forget newlines - write_to_channel(&mut output_channel, "\n").await?; + // save redacted message + log_messages.push(line); } } - Ok(()) + Ok(log_messages) } /// Redact logs, etc. by replacing Bitcoin and Monero addresses diff --git a/swap/src/common/tracing_util.rs b/swap/src/common/tracing_util.rs index de8bf08c..43086432 100644 --- a/swap/src/common/tracing_util.rs +++ b/swap/src/common/tracing_util.rs @@ -60,7 +60,7 @@ pub fn init( } // now we can use the tracing macros to log messages - tracing::info!(%level_filter, "Initialized tracing"); + tracing::info!(%level_filter, logs_dir=%dir.as_ref().display(), "Initialized tracing"); Ok(()) } diff --git a/swap/src/rpc/methods.rs b/swap/src/rpc/methods.rs index f804e085..0577bf67 100644 --- a/swap/src/rpc/methods.rs +++ b/swap/src/rpc/methods.rs @@ -7,7 +7,9 @@ use anyhow::Result; use jsonrpsee::server::RpcModule; use jsonrpsee::types::Params; use libp2p::core::Multiaddr; +use serde::Deserialize; use std::collections::HashMap; +use std::path::PathBuf; use std::str::FromStr; use std::sync::Arc; use uuid::Uuid; @@ -48,8 +50,21 @@ pub fn register_modules(context: Arc) -> Result> execute_request(params_raw, Method::Balance { force_refresh }, &context).await })?; - module.register_async_method("get_history", |params, context| async move { - execute_request(params, Method::History, &context).await + module.register_async_method("get_history", |params_raw, context| async move { + execute_request(params_raw, Method::History, &context).await + })?; + + module.register_async_method("get_logs", |params_raw, context| async move { + #[derive(Debug, Clone, Deserialize)] + struct Params { + swap_id: Option, + logs_dir: Option, + redact: bool + } + + let params: Params = params_raw.parse()?; + + execute_request(params_raw, Method::Logs { swap_id: params.swap_id, logs_dir: params.logs_dir, redact: params.redact }, &context).await })?; module.register_async_method("get_raw_states", |params, context| async move {