Skip to content

Commit bfddd4c

Browse files
committed
refactor: update FilesystemLogWriter to FileWriter
1. Remove left-over log_dir & log_file_path related fields from Config 2. Rename log_dir to log_file_path 3. Update the creation of new FileWriter to handle recursive parent directory 4. Fix integration tests
1 parent 974ee28 commit bfddd4c

File tree

5 files changed

+31
-44
lines changed

5 files changed

+31
-44
lines changed

src/builder.rs

Lines changed: 3 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,7 @@ use crate::io::sqlite_store::SqliteStore;
1818
use crate::io::utils::{read_node_metrics, write_node_metrics};
1919
use crate::io::vss_store::VssStore;
2020
use crate::liquidity::LiquiditySource;
21-
use crate::logger::{
22-
default_format, log_error, log_info, FilesystemLogWriter, LdkNodeLogger, Logger,
23-
};
21+
use crate::logger::{default_format, log_error, log_info, FileWriter, LdkNodeLogger, Logger};
2422
use crate::message_handler::NodeCustomMessageHandler;
2523
use crate::payment::store::PaymentStore;
2624
use crate::peer_store::PeerStore;
@@ -302,12 +300,6 @@ impl NodeBuilder {
302300
self
303301
}
304302

305-
/// Sets the log file path if the log file needs to live separate from the storage directory path.
306-
pub fn set_log_file_path(&mut self, log_dir_path: String) -> &mut Self {
307-
self.config.log_file_path = Some(log_dir_path);
308-
self
309-
}
310-
311303
/// Sets the Bitcoin network used.
312304
pub fn set_network(&mut self, network: Network) -> &mut Self {
313305
self.config.network = network;
@@ -608,11 +600,6 @@ impl ArcedNodeBuilder {
608600
self.inner.write().unwrap().set_storage_dir_path(storage_dir_path);
609601
}
610602

611-
/// Sets the log file path if logs need to live separate from the storage directory path.
612-
pub fn set_log_file_path(&self, log_file_path: String) {
613-
self.inner.write().unwrap().set_log_file_path(log_file_path);
614-
}
615-
616603
/// Sets the Bitcoin network used.
617604
pub fn set_network(&self, network: Network) {
618605
self.inner.write().unwrap().set_network(network);
@@ -633,11 +620,6 @@ impl ArcedNodeBuilder {
633620
self.inner.write().unwrap().set_node_alias(node_alias).map(|_| ())
634621
}
635622

636-
/// Sets the level at which [`Node`] will log messages.
637-
pub fn set_log_level(&self, level: LogLevel) {
638-
self.inner.write().unwrap().set_log_level(level);
639-
}
640-
641623
/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
642624
/// previously configured.
643625
pub fn build(&self) -> Result<Arc<Node>, BuildError> {
@@ -1234,8 +1216,8 @@ fn build_with_store_internal(
12341216
fn setup_logger(config: &Config) -> Result<Arc<LdkNodeLogger>, BuildError> {
12351217
match config.logging_config {
12361218
LoggingConfig::Custom(ref logger) => Ok(logger.clone()),
1237-
LoggingConfig::Filesystem { ref log_dir, log_level } => {
1238-
let filesystem_log_writer = FilesystemLogWriter::new(log_dir.clone())
1219+
LoggingConfig::Filesystem { ref log_file_path, log_level } => {
1220+
let filesystem_log_writer = FileWriter::new(log_file_path.clone())
12391221
.map_err(|_| BuildError::LoggerSetupFailed)?;
12401222
Ok(Arc::new(
12411223
LdkNodeLogger::new(

src/config.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use bitcoin::Network;
2323
use std::time::Duration;
2424

2525
// Config defaults
26-
const DEFAULT_STORAGE_DIR_PATH: &str = "/tmp/ldk_node/";
26+
const DEFAULT_STORAGE_DIR_PATH: &str = "/tmp/ldk_node";
2727
const DEFAULT_NETWORK: Network = Network::Bitcoin;
2828
const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
2929
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
@@ -104,12 +104,7 @@ pub(crate) const WALLET_KEYS_SEED_LEN: usize = 64;
104104
pub struct Config {
105105
/// The path where the underlying LDK and BDK persist their data.
106106
pub storage_dir_path: String,
107-
/// The path where logs are stored.
108-
///
109-
/// If set to `None`, logs can be found in `ldk_node.log` in the [`Config::storage_dir_path`]
110-
/// directory.
111-
pub log_file_path: Option<String>,
112-
/// In the default configuration logs can be found in the `logs` subdirectory in
107+
/// In the default configuration logs can be found in the [`DEFAULT_STORAGE_DIR_PATH`] subdirectory in
113108
/// [`Config::storage_dir_path`], and the log level is set to [`DEFAULT_LOG_LEVEL`].
114109
pub logging_config: LoggingConfig,
115110
/// The used Bitcoin network.
@@ -168,7 +163,6 @@ impl Default for Config {
168163
fn default() -> Self {
169164
Self {
170165
storage_dir_path: DEFAULT_STORAGE_DIR_PATH.to_string(),
171-
log_file_path: None,
172166
logging_config: LoggingConfig::default(),
173167
network: DEFAULT_NETWORK,
174168
listening_addresses: None,
@@ -190,7 +184,7 @@ pub enum LoggingConfig {
190184
/// most recent log file, which is created and timestamped at initialization.
191185
Filesystem {
192186
/// The absolute path where logs are stored.
193-
log_dir: String,
187+
log_file_path: String,
194188
/// The level at which we log messages.
195189
///
196190
/// Any messages below this level will be excluded from the logs.
@@ -203,7 +197,7 @@ pub enum LoggingConfig {
203197
impl Default for LoggingConfig {
204198
fn default() -> Self {
205199
Self::Filesystem {
206-
log_dir: format!("{}/{}", DEFAULT_STORAGE_DIR_PATH, "logs"),
200+
log_file_path: format!("{}/{}", DEFAULT_STORAGE_DIR_PATH, "ldk_node.log"),
207201
log_level: DEFAULT_LOG_LEVEL,
208202
}
209203
}

src/logger.rs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use chrono::Utc;
1515
use std::fmt::Debug;
1616
use std::fs;
1717
use std::io::Write;
18+
use std::path::Path;
1819
use std::sync::Mutex;
1920

2021
pub struct LdkNodeLogger {
@@ -47,20 +48,27 @@ impl Logger for LdkNodeLogger {
4748
}
4849
}
4950

50-
pub(crate) struct FilesystemLogWriter {
51+
pub(crate) struct FileWriter {
5152
log_file: Mutex<fs::File>,
5253
}
5354

54-
impl FilesystemLogWriter {
55-
/// Creates a new filesystem logger.
55+
impl FileWriter {
56+
/// Creates a new filesystem writer.
5657
pub(crate) fn new(log_file_path: String) -> Result<Self, ()> {
58+
if let Some(parent_dir) = Path::new(&log_file_path).parent() {
59+
fs::create_dir_all(parent_dir).map_err(|e| {
60+
eprintln!("ERROR: Failed to create log file directory: {}", e);
61+
()
62+
})?;
63+
}
64+
5765
let log_file = Mutex::new(
58-
fs::OpenOptions::new()
59-
.create(true)
60-
.append(true)
61-
.open(log_file_path.clone())
62-
.map_err(|e| eprintln!("ERROR: Failed to open log file: {}", e))?,
66+
fs::OpenOptions::new().create(true).append(true).open(&log_file_path).map_err(|e| {
67+
eprintln!("ERROR: Failed to open log file: {}", e);
68+
()
69+
})?,
6370
);
71+
6472
Ok(Self { log_file })
6573
}
6674

tests/common/mod.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
use ldk_node::config::{Config, EsploraSyncConfig};
1212
use ldk_node::io::sqlite_store::SqliteStore;
1313
use ldk_node::payment::{PaymentDirection, PaymentKind, PaymentStatus};
14-
use ldk_node::{Builder, Event, LightningBalance, LogLevel, Node, NodeError, PendingSweepBalance};
14+
use ldk_node::{Builder, Event, LightningBalance, Node, NodeError, PendingSweepBalance};
1515

1616
use lightning::ln::msgs::SocketAddress;
1717
use lightning::ln::{PaymentHash, PaymentPreimage};
@@ -231,8 +231,6 @@ pub(crate) fn random_config(anchor_channels: bool) -> Config {
231231
println!("Setting random LDK node alias: {:?}", alias);
232232
config.node_alias = alias;
233233

234-
config.log_level = LogLevel::Gossip;
235-
236234
config
237235
}
238236

tests/integration_tests_rust.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,8 +234,13 @@ fn start_stop_reinit() {
234234
node.sync_wallets().unwrap();
235235
assert_eq!(node.list_balances().spendable_onchain_balance_sats, expected_amount.to_sat());
236236

237-
let log_file = format!("{}/ldk_node.log", config.clone().storage_dir_path);
238-
assert!(std::path::Path::new(&log_file).exists());
237+
let log_conf = &config.logging_config;
238+
match log_conf {
239+
ldk_node::config::LoggingConfig::Filesystem { log_file_path, log_level: _ } => {
240+
assert!(std::path::Path::new(&log_file_path).exists());
241+
},
242+
ldk_node::config::LoggingConfig::Custom(_) => (),
243+
}
239244

240245
node.stop().unwrap();
241246
assert_eq!(node.stop(), Err(NodeError::NotRunning));

0 commit comments

Comments
 (0)