refactor: unify tracing utitilies for asb and cli

This commit is contained in:
Einliterflasche 2024-08-14 14:48:55 +02:00
parent defc94d0b7
commit e56b7dbccf
8 changed files with 31 additions and 129 deletions

View File

@ -1,14 +1,17 @@
pub mod request;
use crate::cli::command::{Bitcoin, Monero, Tor};
use crate::common::tracing_util::Format;
use crate::database::{open_db, AccessMode};
use crate::env::{Config as EnvConfig, GetConfig, Mainnet, Testnet};
use crate::fs::system_data_dir;
use crate::network::rendezvous::XmrBtcNamespace;
use crate::protocol::Database;
use crate::seed::Seed;
use crate::{bitcoin, cli, monero};
use crate::{bitcoin, common, monero};
use anyhow::{bail, Context as AnyContext, Error, Result};
use futures::future::try_join_all;
use tracing::level_filters::LevelFilter;
use tracing::Level;
use std::fmt;
use std::future::Future;
use std::net::SocketAddr;
@ -184,8 +187,15 @@ impl Context {
let data_dir = data::data_dir_from(data, is_testnet)?;
let env_config = env_config_from(is_testnet);
let format = if json { Format::Json } else { Format::Raw };
let level_filter = if debug {
LevelFilter::from_level(Level::DEBUG)
} else {
LevelFilter::from_level(Level::INFO)
};
START.call_once(|| {
let _ = cli::tracing::init(debug, json, data_dir.join("logs"));
let _ = common::tracing_util::init(level_filter, format, data_dir.join("logs"));
});
let seed = Seed::from_file_or_generate(data_dir.as_path())

View File

@ -834,7 +834,7 @@ impl Request {
pub async fn call(self, context: Arc<Context>) -> Result<serde_json::Value> {
let method_span = self.cmd.get_tracing_span(self.log_reference.clone());
self.handle_cmd(context)
.instrument(method_span.clone())
.await

View File

@ -4,7 +4,6 @@ mod event_loop;
mod network;
mod rate;
mod recovery;
pub mod tracing;
pub use event_loop::{EventLoop, EventLoopHandle, FixedRate, KrakenRate, LatestRate};
pub use network::behaviour::{Behaviour, OutEvent};

View File

@ -18,7 +18,7 @@ use libp2p::core::multiaddr::Protocol;
use libp2p::core::Multiaddr;
use libp2p::swarm::AddressScore;
use libp2p::Swarm;
use swap::asb::tracing::Format;
use swap::common::tracing_util::Format;
use std::convert::TryInto;
use std::fs::read_dir;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
@ -39,7 +39,7 @@ use swap::network::swarm;
use swap::protocol::alice::{run, AliceState};
use swap::seed::Seed;
use swap::tor::AuthenticatedClient;
use swap::{asb, bitcoin, kraken, monero, tor};
use swap::{bitcoin, kraken, monero, tor};
use tokio::fs::{create_dir_all, try_exists, File};
use tokio::io::{stdout, AsyncBufReadExt, AsyncWriteExt, BufReader, Stdout};
use tracing_subscriber::filter::LevelFilter;
@ -77,7 +77,7 @@ async fn main() -> Result<()> {
// initialize tracing
let format = if json { Format::Json } else { Format::Raw };
let log_dir = system_data_dir()?.join("logs");
asb::tracing::init(LevelFilter::DEBUG, format, log_dir)
common::tracing_util::init(LevelFilter::DEBUG, format, log_dir)
.expect("initialize tracing");
// read config from the specified path

View File

@ -3,7 +3,6 @@ pub mod cancel_and_refund;
pub mod command;
mod event_loop;
mod list_sellers;
pub mod tracing;
pub mod transport;
pub use behaviour::{Behaviour, OutEvent};

View File

@ -1,112 +0,0 @@
use anyhow::Result;
use std::path::Path;
use time::format_description::well_known::Rfc3339;
use tracing::subscriber::set_global_default;
use tracing::{Event, Level, Subscriber};
use tracing_subscriber::fmt::format::{DefaultFields, Format, JsonFields};
use tracing_subscriber::fmt::time::UtcTime;
use tracing_subscriber::layer::{Context, SubscriberExt};
use tracing_subscriber::{fmt, EnvFilter, Layer, Registry};
pub fn init(debug: bool, json: bool, dir: impl AsRef<Path>) -> Result<()> {
let level_filter = EnvFilter::try_new("swap=debug")?;
let registry = Registry::default().with(level_filter);
let appender = tracing_appender::rolling::never(dir.as_ref(), "swap-all.log");
let file_logger = registry.with(
fmt::layer()
.with_ansi(false)
.with_target(false)
.json()
.with_writer(appender),
);
if json && debug {
set_global_default(file_logger.with(debug_json_terminal_printer()))?;
} else if json && !debug {
set_global_default(file_logger.with(info_json_terminal_printer()))?;
} else if !json && debug {
set_global_default(file_logger.with(debug_terminal_printer()))?;
} else {
set_global_default(file_logger.with(info_terminal_printer()))?;
}
tracing::info!("Logging initialized to {}", dir.as_ref().display());
Ok(())
}
pub struct StdErrPrinter<L> {
inner: L,
level: Level,
}
type StdErrLayer<S, T> =
fmt::Layer<S, DefaultFields, Format<fmt::format::Full, T>, fn() -> std::io::Stderr>;
type StdErrJsonLayer<S, T> =
fmt::Layer<S, JsonFields, Format<fmt::format::Json, T>, fn() -> std::io::Stderr>;
fn debug_terminal_printer<S>() -> StdErrPrinter<StdErrLayer<S, UtcTime<Rfc3339>>> {
let is_terminal = atty::is(atty::Stream::Stderr);
StdErrPrinter {
inner: fmt::layer()
.with_ansi(is_terminal)
.with_target(false)
.with_timer(UtcTime::rfc_3339())
.with_writer(std::io::stderr),
level: Level::DEBUG,
}
}
fn debug_json_terminal_printer<S>() -> StdErrPrinter<StdErrJsonLayer<S, UtcTime<Rfc3339>>> {
let is_terminal = atty::is(atty::Stream::Stderr);
StdErrPrinter {
inner: fmt::layer()
.with_ansi(is_terminal)
.with_target(false)
.with_timer(UtcTime::rfc_3339())
.json()
.with_writer(std::io::stderr),
level: Level::DEBUG,
}
}
fn info_terminal_printer<S>() -> StdErrPrinter<StdErrLayer<S, ()>> {
let is_terminal = atty::is(atty::Stream::Stderr);
StdErrPrinter {
inner: fmt::layer()
.with_ansi(is_terminal)
.with_target(false)
.with_level(false)
.without_time()
.with_writer(std::io::stderr),
level: Level::INFO,
}
}
fn info_json_terminal_printer<S>() -> StdErrPrinter<StdErrJsonLayer<S, ()>> {
let is_terminal = atty::is(atty::Stream::Stderr);
StdErrPrinter {
inner: fmt::layer()
.with_ansi(is_terminal)
.with_target(false)
.with_level(false)
.without_time()
.json()
.with_writer(std::io::stderr),
level: Level::INFO,
}
}
impl<L, S> Layer<S> for StdErrPrinter<L>
where
L: 'static + Layer<S>,
S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
{
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
if self.level.ge(event.metadata().level()) {
self.inner.on_event(event, ctx);
}
}
}

View File

@ -1,3 +1,5 @@
pub mod tracing_util;
use std::collections::HashMap;
use anyhow::anyhow;

View File

@ -4,28 +4,32 @@ use anyhow::Result;
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::fmt::time::UtcTime;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::fmt;
use tracing_subscriber::{fmt, Layer};
use tracing_subscriber::util::SubscriberInitExt;
/// Output formats for logging messages.
pub enum Format {
/// Standard, human readable format.
Raw,
/// Machine readable format.
/// JSON, machine readable format.
Json,
}
/// Initialize tracing and enable logging messages according to these options.
/// Besides printing to `stdout`, this will append to a log file.
/// Said file will contain JSON-formatted logs of all levels,
/// disregarding the arguments to this function.
pub fn init(
level: LevelFilter,
level_filter: LevelFilter,
format: Format,
dir: impl AsRef<Path>,
) -> Result<()> {
if level == LevelFilter::OFF {
if level_filter == LevelFilter::OFF {
return Ok(());
}
// file logger will always write in JSON format and with timestamps
let file_appender = tracing_appender::rolling::never(dir.as_ref(), "swap-all.log");
let file_appender = tracing_appender::rolling::never(&dir, "swap-all.log");
let file_layer = fmt::layer()
.with_writer(file_appender)
@ -36,7 +40,7 @@ pub fn init(
// terminal logger
let is_terminal = atty::is(atty::Stream::Stderr);
let terminal_layer = fmt::layer()
let terminal_layer = fmt::layer()
.with_writer(std::io::stdout)
.with_ansi(is_terminal)
.with_timer(UtcTime::rfc_3339())
@ -46,17 +50,17 @@ pub fn init(
if let Format::Json = format {
tracing_subscriber::registry()
.with(file_layer)
.with(terminal_layer.json())
.with(terminal_layer.json().with_filter(level_filter))
.init();
} else {
tracing_subscriber::registry()
.with(file_layer)
.with(terminal_layer)
.with(terminal_layer.with_filter(level_filter))
.init();
}
// now we can use the tracing macros to log messages
tracing::info!(%level, "Initialized tracing");
tracing::info!(%level_filter, "Initialized tracing");
Ok(())
}