Skip to content

Commit

Permalink
Consolidate loggers under logger.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
erdemyerebasmaz committed Mar 21, 2024
1 parent b2bcec9 commit 602afc5
Show file tree
Hide file tree
Showing 9 changed files with 305 additions and 180 deletions.
1 change: 1 addition & 0 deletions libs/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 3 additions & 34 deletions libs/sdk-bindings/src/uniffi_binding.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use anyhow::Result;
use breez_sdk_core::logger::init_uniffi_logger;
use breez_sdk_core::{
error::*, mnemonic_to_seed as sdk_mnemonic_to_seed, parse as sdk_parse_input,
parse_invoice as sdk_parse_invoice, AesSuccessActionDataDecrypted, AesSuccessActionDataResult,
Expand Down Expand Up @@ -27,39 +28,10 @@ use breez_sdk_core::{
SwapAmountType, SwapInfo, SwapStatus, Symbol, TlvEntry, UnspentTransactionOutput,
UrlSuccessActionData,
};
use log::{Level, LevelFilter, Metadata, Record};
use once_cell::sync::{Lazy, OnceCell};
use once_cell::sync::Lazy;
use std::sync::Arc;

static RT: Lazy<tokio::runtime::Runtime> = Lazy::new(|| tokio::runtime::Runtime::new().unwrap());
static LOG_INIT: OnceCell<bool> = OnceCell::new();

struct BindingLogger {
log_stream: Box<dyn LogStream>,
}

impl BindingLogger {
fn init(log_stream: Box<dyn LogStream>) {
let binding_logger = BindingLogger { log_stream };
log::set_boxed_logger(Box::new(binding_logger)).unwrap();
log::set_max_level(LevelFilter::Trace);
}
}

impl log::Log for BindingLogger {
fn enabled(&self, m: &Metadata) -> bool {
// ignore the internal uniffi log to prevent infinite loop.
return m.level() <= Level::Trace && *m.target() != *"breez_sdk_bindings::uniffi_binding";
}

fn log(&self, record: &Record) {
self.log_stream.log(LogEntry {
line: record.args().to_string(),
level: record.level().as_str().to_string(),
});
}
fn flush(&self) {}
}

/// Create a new SDK config with default values
pub fn default_config(
Expand Down Expand Up @@ -107,10 +79,7 @@ pub fn connect(

/// If used, this must be called before `connect`
pub fn set_log_stream(log_stream: Box<dyn LogStream>) -> SdkResult<()> {
LOG_INIT.set(true).map_err(|_| SdkError::Generic {
err: "Log stream already created".into(),
})?;
BindingLogger::init(log_stream);
init_uniffi_logger(log_stream);
Ok(())
}

Expand Down
1 change: 1 addition & 0 deletions libs/sdk-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ ripemd = "0.1"
rand = "0.8"
tiny-bip39 = "1"
tokio = { version = "1", features = ["full"] }
parking_lot = "0.12.1"
prost = "^0.11"
querystring = "1"
rusqlite = { version = "0.29", features = [
Expand Down
37 changes: 3 additions & 34 deletions libs/sdk-core/src/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use std::sync::Arc;

use anyhow::{anyhow, Result};
use flutter_rust_bridge::StreamSink;
use log::{Level, LevelFilter, Metadata, Record};
use once_cell::sync::{Lazy, OnceCell};
use tokio::sync::Mutex;

Expand All @@ -29,6 +28,7 @@ use crate::fiat::{FiatCurrency, Rate};
use crate::input_parser::{self, InputType, LnUrlAuthRequestData};
use crate::invoice::{self, LNInvoice};
use crate::lnurl::pay::model::LnUrlPayResult;
use crate::logger::{init_dart_logger, DartLogger};
use crate::lsp::LspInformation;
use crate::models::{Config, LogEntry, NodeState, Payment, SwapInfo};
use crate::{
Expand All @@ -55,7 +55,6 @@ static BREEZ_SERVICES_INSTANCE: Lazy<Mutex<Option<Arc<BreezServices>>>> =
Lazy::new(|| Mutex::new(None));
static NOTIFICATION_STREAM: OnceCell<StreamSink<BreezEvent>> = OnceCell::new();
static RT: Lazy<tokio::runtime::Runtime> = Lazy::new(|| tokio::runtime::Runtime::new().unwrap());
static LOG_INIT: OnceCell<bool> = OnceCell::new();

/* Breez Services API's */

Expand Down Expand Up @@ -180,10 +179,8 @@ pub fn breez_events_stream(s: StreamSink<BreezEvent>) -> Result<()> {

/// If used, this must be called before `connect`. It can only be called once.
pub fn breez_log_stream(s: StreamSink<LogEntry>) -> Result<()> {
LOG_INIT
.set(true)
.map_err(|_| anyhow!("Log stream already created"))?;
BindingLogger::init(s);
init_dart_logger();
DartLogger::set_stream_sink(s);
Ok(())
}

Expand Down Expand Up @@ -535,34 +532,6 @@ impl EventListener for BindingEventListener {
}
}

struct BindingLogger {
log_stream: StreamSink<LogEntry>,
}

impl BindingLogger {
fn init(log_stream: StreamSink<LogEntry>) {
let binding_logger = BindingLogger { log_stream };
log::set_boxed_logger(Box::new(binding_logger)).unwrap();
log::set_max_level(LevelFilter::Trace);
}
}

impl log::Log for BindingLogger {
fn enabled(&self, m: &Metadata) -> bool {
m.level() <= Level::Trace
}

fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
self.log_stream.add(LogEntry {
line: record.args().to_string(),
level: record.level().as_str().to_string(),
});
}
}
fn flush(&self) {}
}

async fn get_breez_services() -> Result<Arc<BreezServices>, SdkError> {
match BREEZ_SERVICES_INSTANCE.lock().await.as_ref() {
None => Err(SdkError::Generic {
Expand Down
110 changes: 0 additions & 110 deletions libs/sdk-core/src/breez_services.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::cmp::min;
use std::fs::OpenOptions;
use std::io::Write;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
Expand All @@ -10,9 +8,7 @@ use bip39::*;
use bitcoin::hashes::hex::ToHex;
use bitcoin::hashes::{sha256, Hash};
use bitcoin::util::bip32::ChildNumber;
use chrono::Local;
use futures::TryFutureExt;
use log::{LevelFilter, Metadata, Record};
use reqwest::{header::CONTENT_TYPE, Body};
use serde_json::json;
use tokio::sync::{mpsc, watch, Mutex};
Expand Down Expand Up @@ -1592,86 +1588,6 @@ impl BreezServices {
});
}

/// Configures a global SDK logger that will log to file and will forward log events to
/// an optional application-specific logger.
///
/// If called, it should be called before any SDK methods (for example, before `connect`).
///
/// It must be called only once in the application lifecycle. Alternatively, If the application
/// already uses a globally-registered logger, this method shouldn't be called at all.
///
/// ### Arguments
///
/// - `log_dir`: Location where the the SDK log file will be created. The directory must already exist.
///
/// - `app_logger`: Optional application logger.
///
/// If the application is to use it's own logger, but would also like the SDK to log SDK-specific
/// log output to a file in the configured `log_dir`, then do not register the
/// app-specific logger as a global logger and instead call this method with the app logger as an arg.
///
/// ### Logging Configuration
///
/// Setting `breez_sdk_core::input_parser=debug` will include in the logs the raw payloads received
/// when interacting with JSON endpoints, for example those used during all LNURL workflows.
///
/// ### Errors
///
/// An error is thrown if the log file cannot be created in the working directory.
///
/// An error is thrown if a global logger is already configured.
pub fn init_logging(log_dir: &str, app_logger: Option<Box<dyn log::Log>>) -> Result<()> {
let target_log_file = Box::new(
OpenOptions::new()
.create(true)
.append(true)
.open(format!("{log_dir}/sdk.log"))
.map_err(|e| anyhow!("Can't create log file: {e}"))?,
);
let logger = env_logger::Builder::new()
.target(env_logger::Target::Pipe(target_log_file))
.parse_filters(
r#"
debug,
breez_sdk_core::input_parser=warn,
breez_sdk_core::backup=info,
breez_sdk_core::persist::reverseswap=info,
breez_sdk_core::reverseswap=info,
gl_client=debug,
h2=warn,
hyper=warn,
lightning_signer=warn,
reqwest=warn,
rustls=warn,
rustyline=warn,
vls_protocol_signer=warn
"#,
)
.format(|buf, record| {
writeln!(
buf,
"[{} {} {}:{}] {}",
Local::now().format("%Y-%m-%d %H:%M:%S%.3f"),
record.level(),
record.module_path().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.args()
)
})
.build();

let global_logger = GlobalSdkLogger {
logger,
log_listener: app_logger,
};

log::set_boxed_logger(Box::new(global_logger))
.map_err(|e| anyhow!("Failed to set global logger: {e}"))?;
log::set_max_level(LevelFilter::Trace);

Ok(())
}

async fn lookup_chain_service_closing_outspend(
&self,
channel: crate::models::Channel,
Expand Down Expand Up @@ -1852,32 +1768,6 @@ impl BreezServices {
}
}

struct GlobalSdkLogger {
/// SDK internal logger, which logs to file
logger: env_logger::Logger,
/// Optional external log listener, that can receive a stream of log statements
log_listener: Option<Box<dyn log::Log>>,
}
impl log::Log for GlobalSdkLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= log::Level::Trace
}

fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
self.logger.log(record);

if let Some(s) = &self.log_listener.as_ref() {
if s.enabled(record.metadata()) {
s.log(record);
}
}
}
}

fn flush(&self) {}
}

/// A helper struct to configure and build BreezServices
struct BreezServicesBuilder {
config: Config,
Expand Down
1 change: 1 addition & 0 deletions libs/sdk-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ mod breez_services;
mod chain;
mod crypt;
pub mod error;
pub mod logger;
#[rustfmt::skip]
mod node_api; // flutter_rust_bridge_codegen: has to be defined before greenlight; greenlight::node_api
mod greenlight;
Expand Down
Loading

0 comments on commit 602afc5

Please sign in to comment.