Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply env_logger module filters on Dart & UniFFI binding loggers #874

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions libs/Cargo.lock

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

1 change: 1 addition & 0 deletions libs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ version = "0.6.2"
aes = "0.8"
anyhow = { version = "1.0.79", features = ["backtrace"] }
base64 = "0.13.0"
env_logger = "0.10"
bitcoin = "=0.29.2" # Same version as used in gl-client
# Pin the reqwest dependency until macOS linker issue is fixed: https://github.com/seanmonstar/reqwest/issues/2006
hex = "0.4"
Expand Down
1 change: 1 addition & 0 deletions libs/sdk-bindings/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ crate-type = ["staticlib", "cdylib", "lib"]
anyhow = { workspace = true }
breez-sdk-core = { path = "../sdk-core" }
sdk-common = { path = "../sdk-common" }
env_logger = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
uniffi = { version = "0.23.0", features = ["bindgen-tests", "cli"] }
Expand Down
2 changes: 1 addition & 1 deletion libs/sdk-bindings/bindings-csharp/test/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
try
{
var seed = BreezSdkMethods.MnemonicToSeed("repeat hawk combine screen network rhythm ritual social neither casual volcano powder");
BreezSdkMethods.SetLogStream(new LogStreamListener());
BreezSdkMethods.SetLogStream(new LogStreamListener(), LevelFilter.TRACE);
var config = BreezSdkMethods.DefaultConfig(EnvironmentType.PRODUCTION, "code", new NodeConfig.Greenlight(new GreenlightNodeConfig(null, null)));
var connectRequest = new ConnectRequest(config, seed);
BlockingBreezServices sdkServices = BreezSdkMethods.Connect(connectRequest, new SDKListener());
Expand Down
11 changes: 10 additions & 1 deletion libs/sdk-bindings/src/breez_sdk.udl
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,15 @@ dictionary RefundResponse {
string refund_tx_id;
};

enum LevelFilter {
"Off",
"Error",
"Warn",
"Info",
"Debug",
"Trace",
};

interface BlockingBreezServices {

[Throws=SdkError]
Expand Down Expand Up @@ -993,7 +1002,7 @@ namespace breez_sdk {
BlockingBreezServices connect(ConnectRequest req, EventListener listener);

[Throws=SdkError]
void set_log_stream(LogStream log_stream);
void set_log_stream(LogStream log_stream, LevelFilter? filter_level);

[Throws=SdkError]
LNInvoice parse_invoice(string invoice);
Expand Down
82 changes: 60 additions & 22 deletions libs/sdk-bindings/src/uniffi_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::sync::Arc;

use anyhow::Result;
use breez_sdk_core::lnurl::pay::{LnUrlPayResult, LnUrlPaySuccessData};
use breez_sdk_core::logger::{get_filter_level, init_env_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 All @@ -10,7 +11,7 @@ use breez_sdk_core::{
CheckMessageResponse, ClosedChannelPaymentDetails, Config, ConfigureNodeRequest,
ConnectRequest, CurrencyInfo, EnvironmentType, EventListener, FeeratePreset, FiatCurrency,
GreenlightCredentials, GreenlightDeviceCredentials, GreenlightNodeConfig, HealthCheckStatus,
InputType, InvoicePaidDetails, LNInvoice, ListPaymentsRequest, LnPaymentDetails,
InputType, InvoicePaidDetails, LNInvoice, LevelFilter, ListPaymentsRequest, LnPaymentDetails,
LnUrlAuthError, LnUrlAuthRequestData, LnUrlCallbackStatus, LnUrlErrorData, LnUrlPayError,
LnUrlPayErrorData, LnUrlPayRequest, LnUrlPayRequestData, LnUrlWithdrawError,
LnUrlWithdrawRequest, LnUrlWithdrawRequestData, LnUrlWithdrawResult, LnUrlWithdrawSuccessData,
Expand All @@ -31,35 +32,72 @@ use breez_sdk_core::{
SwapAmountType, SwapInfo, SwapStatus, Symbol, TlvEntry, UnspentTransactionOutput,
UrlSuccessActionData,
};
use log::{Level, LevelFilter, Metadata, Record};
use once_cell::sync::{Lazy, OnceCell};
use env_logger::{Logger, Target};
use log::{
error, max_level, set_boxed_logger, set_max_level, Log, Metadata, Record, STATIC_MAX_LEVEL,
};
use once_cell::sync::Lazy;
use std::sync::Once;

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

struct BindingLogger {
/* UniFFI Logger */

static INIT_UNIFFI_LOGGER: Once = Once::new();

fn init_uniffi_logger(log_stream: Box<dyn LogStream>, filter_level: Option<LevelFilter>) {
INIT_UNIFFI_LOGGER.call_once(|| {
UniFFILogger::set_log_stream(log_stream, filter_level);
});
}

struct UniFFILogger {
env_logger: Logger,
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 UniFFILogger {
fn set_log_stream(log_stream: Box<dyn LogStream>, filter_level: Option<LevelFilter>) {
let filter_level = get_filter_level(filter_level);
assert!(
filter_level <= STATIC_MAX_LEVEL,
"Should respect STATIC_MAX_LEVEL={:?}, which is done in compile time. level{:?}",
STATIC_MAX_LEVEL,
filter_level
);

let env_logger = init_env_logger(Some(Target::Stdout), Some(filter_level));

let uniffi_logger = UniFFILogger {
env_logger,
log_stream,
};
set_boxed_logger(Box::new(uniffi_logger))
.unwrap_or_else(|_| error!("Log stream already created."));
set_max_level(filter_level);
}

fn record_to_entry(record: &Record) -> LogEntry {
LogEntry {
line: format!("{}", record.args()),
level: format!("{}", record.level()),
}
}
}

impl log::Log for BindingLogger {
fn enabled(&self, m: &Metadata) -> bool {
impl Log for UniFFILogger {
fn enabled(&self, metadata: &Metadata) -> bool {
// ignore the internal uniffi log to prevent infinite loop.
return m.level() <= Level::Trace && *m.target() != *"breez_sdk_bindings::uniffi_binding";
return metadata.level() <= max_level()
&& *metadata.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(),
});
let metadata = record.metadata();
if self.enabled(metadata) && self.env_logger.enabled(metadata) {
let entry = Self::record_to_entry(record);
self.log_stream.log(entry);
}
}
fn flush(&self) {}
}
Expand Down Expand Up @@ -109,11 +147,11 @@ 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);
pub fn set_log_stream(
log_stream: Box<dyn LogStream>,
filter_level: Option<LevelFilter>,
) -> SdkResult<()> {
init_uniffi_logger(log_stream, filter_level);
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion libs/sdk-bindings/tests/bindings/csharp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
try
{
var seed = BreezSdkMethods.MnemonicToSeed("repeat hawk combine screen network rhythm ritual social neither casual volcano powder");
BreezSdkMethods.SetLogStream(new LogStreamListener());
BreezSdkMethods.SetLogStream(new LogStreamListener(), LevelFilter.TRACE);
var config = BreezSdkMethods.DefaultConfig(EnvironmentType.PRODUCTION, "code", new NodeConfig.Greenlight(new GreenlightNodeConfig(null, null)));
var connectRequest = new ConnectRequest(config, seed);
BlockingBreezServices sdkServices = BreezSdkMethods.Connect(connectRequest, new SDKListener());
Expand Down
4 changes: 3 additions & 1 deletion libs/sdk-bindings/tests/bindings/golang/test_breez_sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ func (BreezListener) OnEvent(e breez_sdk.BreezEvent) {
func main() {
breezListener := BreezListener{}

breez_sdk.SetLogStream(breezListener)
filterLevel := breez_sdk.LevelFilterTrace

breez_sdk.SetLogStream(breezListener, &filterLevel)

seed, err := breez_sdk.MnemonicToSeed("repeat hawk combine screen network rhythm ritual social neither casual volcano powder")

Expand Down
2 changes: 1 addition & 1 deletion libs/sdk-bindings/tests/bindings/test_breez_sdk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
try
{
var seed = BreezSdkMethods.MnemonicToSeed("repeat hawk combine screen network rhythm ritual social neither casual volcano powder");
BreezSdkMethods.SetLogStream(new LogStreamListener());
BreezSdkMethods.SetLogStream(new LogStreamListener(), LevelFilter.TRACE);
var config = BreezSdkMethods.DefaultConfig(EnvironmentType.PRODUCTION, "code", new NodeConfig.Greenlight(new GreenlightNodeConfig(null, null)));
var connectRequest = new ConnectRequest(config, seed);
BlockingBreezServices sdkServices = BreezSdkMethods.Connect(connectRequest, new SDKListener());
Expand Down
29 changes: 17 additions & 12 deletions libs/sdk-bindings/tests/bindings/test_breez_sdk.kts
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@

import breez_sdk.BreezEvent

class SDKListener: breez_sdk.EventListener {
class SDKListener : breez_sdk.EventListener {
override fun onEvent(e: BreezEvent) {
println(e.toString());
println(e.toString())
}
}

class LogStreamListener: breez_sdk.LogStream {
class LogStreamListener : breez_sdk.LogStream {
override fun log(l: breez_sdk.LogEntry) {
if (l.level != "TRACE") {
println(l.line);
println(l.line)
}
}
}

try {
breez_sdk.setLogStream(LogStreamListener());
var seed = breez_sdk.mnemonicToSeed("repeat hawk combine screen network rhythm ritual social neither casual volcano powder");
var config = breez_sdk.defaultConfig(breez_sdk.EnvironmentType.PRODUCTION, "code", breez_sdk.NodeConfig.Greenlight(breez_sdk.GreenlightNodeConfig(null, null)))
breez_sdk.setLogStream(LogStreamListener(), breez_sdk.LevelFilter.TRACE)
var seed = breez_sdk.mnemonicToSeed("repeat hawk combine screen network rhythm ritual social neither casual volcano powder")
var config =
breez_sdk.defaultConfig(
breez_sdk.EnvironmentType.PRODUCTION,
"code",
breez_sdk.NodeConfig.Greenlight(breez_sdk.GreenlightNodeConfig(null, null)),
)
var connectRequest = breez_sdk.ConnectRequest(config, seed)
var sdkServices = breez_sdk.connect(connectRequest, SDKListener());
var nodeInfo = sdkServices.nodeInfo();
assert(nodeInfo.id.equals("027e2b899f9f75b92a1ad210da21d74e7314e3499375213a71c6bf3e1b4b4394a1"));
}catch (ex: Exception) {
var sdkServices = breez_sdk.connect(connectRequest, SDKListener())
var nodeInfo = sdkServices.nodeInfo()
assert(nodeInfo.id.equals("027e2b899f9f75b92a1ad210da21d74e7314e3499375213a71c6bf3e1b4b4394a1"))
} catch (ex: Exception) {
throw RuntimeException(ex.toString())
}
}
2 changes: 1 addition & 1 deletion libs/sdk-bindings/tests/bindings/test_breez_sdk.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class LogStreamListener: LogStream {
}

do {
try setLogStream(logStream: LogStreamListener());
try setLogStream(logStream: LogStreamListener(), filterLevel: LevelFilter.trace);
let seed = try mnemonicToSeed(phrase: "repeat hawk combine screen network rhythm ritual social neither casual volcano powder");
let config = breez_sdk.defaultConfig(envType: EnvironmentType.production, apiKey: "code", nodeConfig: NodeConfig.greenlight(config: GreenlightNodeConfig(partnerCredentials: nil, inviteCode: nil)));
let connectRequest = ConnectRequest(config: config, seed: seed)
Expand Down
3 changes: 2 additions & 1 deletion libs/sdk-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ zbase32 = "0.1.2"
base64 = { workspace = true }
chrono = "0.4"
ecies = { version = "0.2.6", default-features = false, features = ["pure"] }
env_logger = "0.10"
env_logger = { workspace = true }
futures = "0.3.30"
ripemd = "0.1"
rand = "0.8"
tiny-bip39 = "1"
tokio = { workspace = true }
parking_lot = "0.12.3"
prost = { workspace = true }
rusqlite = { workspace = true }
rusqlite_migration = "1.0"
Expand Down
Loading
Loading