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 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
4 changes: 2 additions & 2 deletions 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
35 changes: 33 additions & 2 deletions 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
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ typedef struct wire_cst_ln_invoice {
uint64_t min_final_cltv_expiry_delta;
} wire_cst_ln_invoice;

typedef struct wire_cst_log_entry {
struct wire_cst_list_prim_u_8_strict *line;
struct wire_cst_list_prim_u_8_strict *level;
} wire_cst_log_entry;

typedef struct wire_cst_PaymentError_Generic {
struct wire_cst_list_prim_u_8_strict *err;
} wire_cst_PaymentError_Generic;
Expand Down Expand Up @@ -260,6 +265,9 @@ void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment(in
void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_sync(int64_t port_,
uintptr_t that);

void frbgen_breez_liquid_wire__crate__bindings__breez_log_stream(int64_t port_,
struct wire_cst_list_prim_u_8_strict *s);

void frbgen_breez_liquid_wire__crate__bindings__connect(int64_t port_,
struct wire_cst_connect_request *req);

Expand Down Expand Up @@ -327,6 +335,7 @@ static int64_t dummy_method_to_enforce_bundling(void) {
dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_restore);
dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment);
dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_sync);
dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__breez_log_stream);
dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__connect);
dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__parse_invoice);
dummy_var ^= ((int64_t) (void*) store_dart_post_cobject);
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
2 changes: 1 addition & 1 deletion lib/bindings/langs/react-native/src/gen_kotlin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub use uniffi_bindgen::bindings::kotlin::gen_kotlin::*;
use crate::generator::RNConfig;

static IGNORED_FUNCTIONS: Lazy<HashSet<String>> = Lazy::new(|| {
let list: Vec<&str> = vec!["connect", "add_event_listener"];
let list: Vec<&str> = vec!["connect", "add_event_listener", "set_logger"];
HashSet::from_iter(list.into_iter().map(|s| s.to_string()))
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,21 @@ class BreezLiquidSDKModule(reactContext: ReactApplicationContext) : ReactContext
{%- if func.name()|ignored_function == false -%}
{% include "TopLevelFunctionTemplate.kt" %}
{% endif -%}
{%- endfor %}
{%- endfor %}
@ReactMethod
fun setLogger(promise: Promise) {
executor.execute {
try {
val emitter = reactApplicationContext.getJSModule(RCTDeviceEventEmitter::class.java)

setLogger(BreezLiquidSDKLogger(emitter))
promise.resolve(readableMapOf("status" to "ok"))
} catch (e: Exception) {
e.printStackTrace()
promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e)
}
}
}

@ReactMethod
fun connect(req: ReadableMap, promise: Promise) {
Expand Down
2 changes: 1 addition & 1 deletion lib/bindings/langs/react-native/src/gen_swift/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::generator::RNConfig;
pub use uniffi_bindgen::bindings::swift::gen_swift::*;

static IGNORED_FUNCTIONS: Lazy<HashSet<String>> = Lazy::new(|| {
let list: Vec<&str> = vec!["connect", "add_event_listener"];
let list: Vec<&str> = vec!["connect", "add_event_listener", "set_logger"];
HashSet::from_iter(list.into_iter().map(|s| s.to_string()))
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ @interface RCT_EXTERN_MODULE(RNBreezLiquidSDK, RCTEventEmitter)
{% include "ExternFunctionTemplate.m" %}
{% endif %}
{%- endfor %}
RCT_EXTERN_METHOD(
setLogger: (RCTPromiseResolveBlock)resolve
reject: (RCTPromiseRejectBlock)reject
)

RCT_EXTERN_METHOD(
connect: (NSDictionary*)req
resolve: (RCTPromiseResolveBlock)resolve
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class RNBreezLiquidSDK: RCTEventEmitter {

public static var emitter: RCTEventEmitter!
public static var hasListeners: Bool = false
public static var supportedEvents: [String] = []
public static var supportedEvents: [String] = ["breezLiquidSdkLog"]

private var bindingLiquidSdk: BindingLiquidSdk!

Expand Down Expand Up @@ -62,6 +62,16 @@ class RNBreezLiquidSDK: RCTEventEmitter {
{% include "TopLevelFunctionTemplate.swift" %}
{% endif -%}
{%- endfor %}
@objc(setLogger:reject:)
func setLogger(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
do {
try BreezLiquidSDK.setLogger(Logger: BreezLiquidSDKLogger())
resolve(["status": "ok"])
} catch let err {
rejectErr(err: err, reject: reject)
}
}

@objc(connect:resolve:reject:)
func connect(_ req:[String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
if bindingLiquidSdk != nil {
Expand Down
2 changes: 1 addition & 1 deletion lib/bindings/langs/react-native/src/gen_typescript/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ static KEYWORDS: Lazy<HashSet<String>> = Lazy::new(|| {
});

static IGNORED_FUNCTIONS: Lazy<HashSet<String>> = Lazy::new(|| {
let list: Vec<&str> = vec!["connect", "add_event_listener"];
let list: Vec<&str> = vec!["connect", "add_event_listener", "set_logger"];
HashSet::from_iter(list.into_iter().map(|s| s.to_string()))
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@

export type EventListener = (e: LiquidSdkEvent) => void

export type Logger = (logEntry: LogEntry) => void

export const connect = async (req: ConnectRequest): Promise<void> => {
const response = await BreezLiquidSDK.connect(req)
return response
Expand All @@ -12,3 +14,13 @@ export const addEventListener = async (listener: EventListener): Promise<string>

return response
}

export const setLogger = async (logger: Logger): Promise<EmitterSubscription> => {
const subscription = BreezLiquidSDKEmitter.addListener("breezLiquidSdkLog", logger)

try {
await BreezLiquidSDK.setLogger()
} catch {}

return subscription
}
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 @@ -150,10 +150,22 @@ callback interface EventListener {
void on_event(LiquidSdkEvent e);
};

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

dictionary LogEntry {
string line;
string level;
};

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

[Throws=LiquidSdkError]
void set_logger(Logger logger);

[Throws=PaymentError]
LNInvoice parse_invoice(string invoice);
};
Expand Down
Loading
Loading