Skip to content

Commit 8bfa8ec

Browse files
authored
Merge pull request #454 from tnull/2025-01-fix-env-logger
Fix `log`-facade logging and clarify max level
2 parents b0f4443 + 9f2714c commit 8bfa8ec

File tree

3 files changed

+57
-46
lines changed

3 files changed

+57
-46
lines changed

bindings/ldk_node.udl

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ interface Builder {
6060
void set_gossip_source_rgs(string rgs_server_url);
6161
void set_liquidity_source_lsps2(SocketAddress address, PublicKey node_id, string? token);
6262
void set_storage_dir_path(string storage_dir_path);
63-
void set_filesystem_logger(string? log_file_path, LogLevel? log_level);
64-
void set_log_facade_logger(LogLevel log_level);
63+
void set_filesystem_logger(string? log_file_path, LogLevel? max_log_level);
64+
void set_log_facade_logger(LogLevel? max_log_level);
6565
void set_custom_logger(LogWriter log_writer);
6666
void set_network(Network network);
6767
[Throws=BuildError]

src/builder.rs

+31-16
Original file line numberDiff line numberDiff line change
@@ -111,20 +111,22 @@ impl Default for LiquiditySourceConfig {
111111

112112
#[derive(Clone)]
113113
enum LogWriterConfig {
114-
File { log_file_path: Option<String>, log_level: Option<LogLevel> },
115-
Log(LogLevel),
114+
File { log_file_path: Option<String>, max_log_level: Option<LogLevel> },
115+
Log { max_log_level: Option<LogLevel> },
116116
Custom(Arc<dyn LogWriter>),
117117
}
118118

119119
impl std::fmt::Debug for LogWriterConfig {
120120
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121121
match self {
122-
LogWriterConfig::File { log_level, log_file_path } => f
122+
LogWriterConfig::File { max_log_level, log_file_path } => f
123123
.debug_struct("LogWriterConfig")
124-
.field("log_level", log_level)
124+
.field("max_log_level", max_log_level)
125125
.field("log_file_path", log_file_path)
126126
.finish(),
127-
LogWriterConfig::Log(level) => f.debug_tuple("Log").field(level).finish(),
127+
LogWriterConfig::Log { max_log_level } => {
128+
f.debug_tuple("Log").field(max_log_level).finish()
129+
},
128130
LogWriterConfig::Custom(_) => {
129131
f.debug_tuple("Custom").field(&"<config internal to custom log writer>").finish()
130132
},
@@ -331,19 +333,24 @@ impl NodeBuilder {
331333
///
332334
/// The `log_file_path` defaults to [`DEFAULT_LOG_FILENAME`] in the configured
333335
/// [`Config::storage_dir_path`] if set to `None`.
334-
/// The `log_level` defaults to [`DEFAULT_LOG_LEVEL`] if set to `None`.
336+
///
337+
/// If set, the `max_log_level` sets the maximum log level. Otherwise, the latter defaults to
338+
/// [`DEFAULT_LOG_LEVEL`].
335339
///
336340
/// [`DEFAULT_LOG_FILENAME`]: crate::config::DEFAULT_LOG_FILENAME
337341
pub fn set_filesystem_logger(
338-
&mut self, log_file_path: Option<String>, log_level: Option<LogLevel>,
342+
&mut self, log_file_path: Option<String>, max_log_level: Option<LogLevel>,
339343
) -> &mut Self {
340-
self.log_writer_config = Some(LogWriterConfig::File { log_file_path, log_level });
344+
self.log_writer_config = Some(LogWriterConfig::File { log_file_path, max_log_level });
341345
self
342346
}
343347

344348
/// Configures the [`Node`] instance to write logs to the [`log`](https://crates.io/crates/log) facade.
345-
pub fn set_log_facade_logger(&mut self, log_level: LogLevel) -> &mut Self {
346-
self.log_writer_config = Some(LogWriterConfig::Log(log_level));
349+
///
350+
/// If set, the `max_log_level` sets the maximum log level. Otherwise, the latter defaults to
351+
/// [`DEFAULT_LOG_LEVEL`].
352+
pub fn set_log_facade_logger(&mut self, max_log_level: Option<LogLevel>) -> &mut Self {
353+
self.log_writer_config = Some(LogWriterConfig::Log { max_log_level });
347354
self
348355
}
349356

@@ -658,7 +665,9 @@ impl ArcedNodeBuilder {
658665
///
659666
/// The `log_file_path` defaults to [`DEFAULT_LOG_FILENAME`] in the configured
660667
/// [`Config::storage_dir_path`] if set to `None`.
661-
/// The `log_level` defaults to [`DEFAULT_LOG_LEVEL`] if set to `None`.
668+
///
669+
/// If set, the `max_log_level` sets the maximum log level. Otherwise, the latter defaults to
670+
/// [`DEFAULT_LOG_LEVEL`].
662671
///
663672
/// [`DEFAULT_LOG_FILENAME`]: crate::config::DEFAULT_LOG_FILENAME
664673
pub fn set_filesystem_logger(
@@ -668,7 +677,10 @@ impl ArcedNodeBuilder {
668677
}
669678

670679
/// Configures the [`Node`] instance to write logs to the [`log`](https://crates.io/crates/log) facade.
671-
pub fn set_log_facade_logger(&self, log_level: LogLevel) {
680+
///
681+
/// If set, the `max_log_level` sets the maximum log level. Otherwise, the latter defaults to
682+
/// [`DEFAULT_LOG_LEVEL`].
683+
pub fn set_log_facade_logger(&self, log_level: Option<LogLevel>) {
672684
self.inner.write().unwrap().set_log_facade_logger(log_level);
673685
}
674686

@@ -1305,16 +1317,19 @@ fn setup_logger(
13051317
log_writer_config: &Option<LogWriterConfig>, config: &Config,
13061318
) -> Result<Arc<Logger>, BuildError> {
13071319
let logger = match log_writer_config {
1308-
Some(LogWriterConfig::File { log_file_path, log_level }) => {
1320+
Some(LogWriterConfig::File { log_file_path, max_log_level }) => {
13091321
let log_file_path = log_file_path
13101322
.clone()
13111323
.unwrap_or_else(|| format!("{}/{}", config.storage_dir_path, DEFAULT_LOG_FILENAME));
1312-
let log_level = log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL);
1324+
let max_log_level = max_log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL);
13131325

1314-
Logger::new_fs_writer(log_file_path, log_level)
1326+
Logger::new_fs_writer(log_file_path, max_log_level)
13151327
.map_err(|_| BuildError::LoggerSetupFailed)?
13161328
},
1317-
Some(LogWriterConfig::Log(log_level)) => Logger::new_log_facade(*log_level),
1329+
Some(LogWriterConfig::Log { max_log_level }) => {
1330+
let max_log_level = max_log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL);
1331+
Logger::new_log_facade(max_log_level)
1332+
},
13181333

13191334
Some(LogWriterConfig::Custom(custom_log_writer)) => {
13201335
Logger::new_custom_writer(Arc::clone(&custom_log_writer))

src/logger.rs

+24-28
Original file line numberDiff line numberDiff line change
@@ -106,18 +106,18 @@ pub trait LogWriter: Send + Sync {
106106
/// Defines a writer for [`Logger`].
107107
pub(crate) enum Writer {
108108
/// Writes logs to the file system.
109-
FileWriter { file_path: String, level: LogLevel },
109+
FileWriter { file_path: String, max_log_level: LogLevel },
110110
/// Forwards logs to the `log` facade.
111-
LogFacadeWriter { level: LogLevel },
111+
LogFacadeWriter { max_log_level: LogLevel },
112112
/// Forwards logs to a custom writer.
113113
CustomWriter(Arc<dyn LogWriter>),
114114
}
115115

116116
impl LogWriter for Writer {
117117
fn log(&self, record: LogRecord) {
118118
match self {
119-
Writer::FileWriter { file_path, level } => {
120-
if record.level < *level {
119+
Writer::FileWriter { file_path, max_log_level } => {
120+
if record.level < *max_log_level {
121121
return;
122122
}
123123

@@ -138,28 +138,24 @@ impl LogWriter for Writer {
138138
.write_all(log.as_bytes())
139139
.expect("Failed to write to log file")
140140
},
141-
Writer::LogFacadeWriter { level } => {
141+
Writer::LogFacadeWriter { max_log_level } => {
142+
if record.level < *max_log_level {
143+
return;
144+
}
142145
macro_rules! log_with_level {
143-
($log_level:expr, $($args:tt)*) => {
146+
($log_level:expr, $target: expr, $($args:tt)*) => {
144147
match $log_level {
145-
LogLevel::Gossip | LogLevel::Trace => trace!($($args)*),
146-
LogLevel::Debug => debug!($($args)*),
147-
LogLevel::Info => info!($($args)*),
148-
LogLevel::Warn => warn!($($args)*),
149-
LogLevel::Error => error!($($args)*),
148+
LogLevel::Gossip | LogLevel::Trace => trace!(target: $target, $($args)*),
149+
LogLevel::Debug => debug!(target: $target, $($args)*),
150+
LogLevel::Info => info!(target: $target, $($args)*),
151+
LogLevel::Warn => warn!(target: $target, $($args)*),
152+
LogLevel::Error => error!(target: $target, $($args)*),
150153
}
151154
};
152155
}
153156

154-
log_with_level!(
155-
level,
156-
"{} {:<5} [{}:{}] {}",
157-
Utc::now().format("%Y-%m-%d %H:%M:%S"),
158-
record.level,
159-
record.module_path,
160-
record.line,
161-
record.args
162-
)
157+
let target = format!("[{}:{}]", record.module_path, record.line);
158+
log_with_level!(record.level, &target, " {}", record.args)
163159
},
164160
Writer::CustomWriter(custom_logger) => custom_logger.log(record),
165161
}
@@ -174,7 +170,7 @@ pub(crate) struct Logger {
174170
impl Logger {
175171
/// Creates a new logger with a filesystem writer. The parameters to this function
176172
/// are the path to the log file, and the log level.
177-
pub fn new_fs_writer(file_path: String, level: LogLevel) -> Result<Self, ()> {
173+
pub fn new_fs_writer(file_path: String, max_log_level: LogLevel) -> Result<Self, ()> {
178174
if let Some(parent_dir) = Path::new(&file_path).parent() {
179175
fs::create_dir_all(parent_dir)
180176
.map_err(|e| eprintln!("ERROR: Failed to create log parent directory: {}", e))?;
@@ -187,11 +183,11 @@ impl Logger {
187183
.map_err(|e| eprintln!("ERROR: Failed to open log file: {}", e))?;
188184
}
189185

190-
Ok(Self { writer: Writer::FileWriter { file_path, level } })
186+
Ok(Self { writer: Writer::FileWriter { file_path, max_log_level } })
191187
}
192188

193-
pub fn new_log_facade(level: LogLevel) -> Self {
194-
Self { writer: Writer::LogFacadeWriter { level } }
189+
pub fn new_log_facade(max_log_level: LogLevel) -> Self {
190+
Self { writer: Writer::LogFacadeWriter { max_log_level } }
195191
}
196192

197193
pub fn new_custom_writer(log_writer: Arc<dyn LogWriter>) -> Self {
@@ -202,14 +198,14 @@ impl Logger {
202198
impl LdkLogger for Logger {
203199
fn log(&self, record: LdkRecord) {
204200
match &self.writer {
205-
Writer::FileWriter { file_path: _, level } => {
206-
if record.level < *level {
201+
Writer::FileWriter { file_path: _, max_log_level } => {
202+
if record.level < *max_log_level {
207203
return;
208204
}
209205
self.writer.log(record.into());
210206
},
211-
Writer::LogFacadeWriter { level } => {
212-
if record.level < *level {
207+
Writer::LogFacadeWriter { max_log_level } => {
208+
if record.level < *max_log_level {
213209
return;
214210
}
215211
self.writer.log(record.into());

0 commit comments

Comments
 (0)