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

Add global SDK logger #242

Merged
merged 21 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion cli/Cargo.lock

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

1 change: 0 additions & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ anyhow = "1.0.80"
bip39 = "2.0.0"
breez-liquid-sdk = { path = "../lib/core" }
clap = { version = "4.5.1", features = ["derive"] }
env_logger = "0.11"
log = "0.4.20"
qrcode-rs = { version = "0.1", default-features = false }
rustyline = { version = "13.0.0", features = ["derive"] }
Expand Down
11 changes: 0 additions & 11 deletions cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,3 @@ To specify a custom data directory, use
```bash
cargo run -- --data-dir temp-dir
```

To set a custom log level, use

```bash
RUST_LOG=info|debug|warn cargo run
```

To specify a file to pipe logs to, use
```bash
RUST_LOG=info|debug|warn cargo run -- --log-file /tmp/log
```
23 changes: 2 additions & 21 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
mod commands;
mod persist;

use std::{
fs::{self, OpenOptions},
path::PathBuf,
};
use std::{fs, path::PathBuf};

use anyhow::{anyhow, Result};
use breez_liquid_sdk::{
Expand Down Expand Up @@ -61,23 +58,7 @@ async fn main() -> Result<()> {
let data_dir = PathBuf::from(&data_dir_str);
fs::create_dir_all(&data_dir)?;

let log_path = args.log_file.unwrap_or(
data_dir
.join("cli.log")
.to_str()
.ok_or(anyhow!("Could not create log file"))?
.to_string(),
);
let log_file = OpenOptions::new()
.create(true)
.append(true)
.open(log_path)?;

env_logger::builder()
.target(env_logger::Target::Pipe(Box::new(log_file)))
.filter(None, log::LevelFilter::Debug)
.filter(Some("rustyline"), log::LevelFilter::Warn)
.init();
LiquidSdk::init_logging(&data_dir_str, None)?;

let persistence = CliPersistence { data_dir };
let history_file = &persistence.history_file();
Expand Down
34 changes: 33 additions & 1 deletion lib/Cargo.lock

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

2 changes: 2 additions & 0 deletions lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ version = "0.0.1"

[workspace.dependencies]
anyhow = "1.0"
log = "0.4.20"
once_cell = "1.19"
thiserror = "1.0"
uniffi = "0.27.1"
uniffi_macros = "0.27.1"
Expand Down
3 changes: 2 additions & 1 deletion lib/bindings/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@ crate-type = ["staticlib", "cdylib", "lib"]
[dependencies]
anyhow = { workspace = true }
breez-liquid-sdk = { path = "../core" }
log = { workspace = true }
uniffi = { workspace = true, features = [ "bindgen-tests", "cli" ] }
# Bindgen used by KMP, version has to match the one supported by KMP
uniffi_bindgen = "0.25.2"
uniffi-kotlin-multiplatform = { git = "https://gitlab.com/trixnity/uniffi-kotlin-multiplatform-bindings", rev = "55d51f3abf9819b32bd81756053dcfc10f8d5522" }
camino = "1.1.1"
thiserror = { workspace = true }
tokio = { version = "1", features = ["rt"] }
once_cell = "*"
once_cell = { workspace = true }

[build-dependencies]
uniffi = { workspace = true, features = [ "build" ] }
Expand Down
4 changes: 2 additions & 2 deletions lib/bindings/langs/react-native/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ uniffi = { version = "0.23.0", features = ["bindgen-tests", "cli"] }
uniffi_bindgen = "0.23.0"
uniffi_macros = "0.23.0"
camino = "1.1.1"
log = "*"
log = { workspace = true }
serde = "*"
askama = { version = "0.11.1", default-features = false, features = ["config"] }
toml = "0.5"
clap = { version = "3.2.22", features = ["derive"] }
heck = "0.4"
paste = "1.0"
once_cell = "1.12"
once_cell = { workspace = true }

[build-dependencies]
uniffi_build = { version = "0.23.0" }
Expand Down
12 changes: 12 additions & 0 deletions lib/bindings/src/breez_liquid_sdk.udl
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,21 @@ callback interface EventListener {
void on_event(LiquidSdkEvent e);
};

callback interface LogStream {
void log(LogEntry l);
};

dictionary LogEntry {
string line;
string level;
};

namespace breez_liquid_sdk {
[Throws=LiquidSdkError]
BindingLiquidSdk connect(ConnectRequest req);

[Throws=LiquidSdkError]
void set_log_stream(LogStream log_stream);
ok300 marked this conversation as resolved.
Show resolved Hide resolved
};

interface BindingLiquidSdk {
Expand Down
44 changes: 43 additions & 1 deletion lib/bindings/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,58 @@
use std::sync::Arc;

use anyhow::Result;
use log::{Metadata, Record};
use breez_liquid_sdk::{error::*, model::*, sdk::LiquidSdk};
use once_cell::sync::Lazy;
use breez_liquid_sdk::sdk::LogStream;
use once_cell::sync::{Lazy, OnceCell};
use tokio::runtime::Runtime;
use uniffi::deps::log::{Level, LevelFilter};

static RT: Lazy<Runtime> = Lazy::new(|| Runtime::new().unwrap());

fn rt() -> &'static Runtime {
&RT
}

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_liquid_sdk::breez_liquid_sdk_bindings";
ok300 marked this conversation as resolved.
Show resolved Hide resolved
}

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) {}
}


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

pub fn connect(req: ConnectRequest) -> Result<Arc<BindingLiquidSdk>, LiquidSdkError> {
rt().block_on(async {
let sdk = LiquidSdk::connect(req).await?;
Expand Down
6 changes: 4 additions & 2 deletions lib/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ anyhow = { workspace = true }
bip39 = { version = "2.0.0", features = ["serde"] }
#boltz-client = { git = "https://github.com/SatoshiPortal/boltz-rust", rev = "a05731cc33030ada9ae14afcafe0cded22842ba6" }
boltz-client = { git = "https://github.com/ok300/boltz-rust", branch = "ok300-breez-latest-05-27" }
chrono = "0.4"
env_logger = "0.11"
flutter_rust_bridge = { version = "=2.0.0-dev.36", features = ["chrono"], optional = true }
log = "0.4.20"
log = { workspace = true }
lwk_common = "0.5.1"
lwk_signer = "0.5.1"
# Switch back to published version once this PR is merged: https://github.com/Blockstream/lwk/pull/34
Expand All @@ -29,7 +31,7 @@ serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.116"
thiserror = { workspace = true }
tokio-tungstenite = { version = "0.21.0", features = ["native-tls-vendored"] }
once_cell = "1"
once_cell = { workspace = true }
openssl = { version = "0.10", features = ["vendored"] }
tokio = { version = "1", features = ["rt"] }
url = "2.5.0"
Expand Down
7 changes: 7 additions & 0 deletions lib/core/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,13 @@ impl Payment {
}
}

/// Internal SDK log entry
#[derive(Clone, Debug)]
pub struct LogEntry {
pub line: String,
pub level: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct InternalLeaf {
pub output: String,
Expand Down
Loading
Loading