fix: log paths and remove -o flag

This commit is contained in:
Einliterflasche 2024-08-19 15:49:14 +02:00
parent f29f62a045
commit a99d9ba7f4
7 changed files with 54 additions and 96 deletions

View File

@ -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<PathBuf>,
output_path: Option<PathBuf>,
redact: bool,
swap_id: Option<Uuid>
},
@ -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?;

View File

@ -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<PathBuf>,
output_path: Option<PathBuf>,
swap_id: Option<Uuid>,
redact: bool,
},
@ -287,11 +284,6 @@ pub enum RawCommand {
help = "Print the logs from this directory instead of the default one."
)]
logs_dir: Option<PathBuf>,
#[structopt(
short = "o",
help = "Print the logs into this file instead of the terminal."
)]
output_path: Option<PathBuf>,
#[structopt(
help = "Redact swap-ids, Bitcoin and Monero addresses.",
long = "redact"

View File

@ -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?;

View File

@ -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<PathBuf>,
#[structopt(
short = "o",
help = "Print the logs into this file instead of the terminal."
)]
output_path: Option<PathBuf>,
#[structopt(
help = "Redact swap-ids, Bitcoin and Monero addresses.",
long = "redact"

View File

@ -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<regex::Regex> = 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<PathBuf>, output_path: Option<PathBuf>, swap_id: Option<Uuid>, 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<Uuid>, redact_addresses: bool) -> anyhow::Result<Vec<String>> {
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<dyn Fn(&str) -> 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<PathBuf>, 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

View File

@ -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(())
}

View File

@ -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<Context>) -> Result<RpcModule<Arc<Context>>
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<Uuid>,
logs_dir: Option<PathBuf>,
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 {