Skip to content

Commit 973636b

Browse files
henghongleejkczyz
authored andcommitted
Add WithContext and Tests
1 parent a42aeb5 commit 973636b

File tree

3 files changed

+90
-4
lines changed

3 files changed

+90
-4
lines changed

lightning/src/ln/channel.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ use crate::sign::{EntropySource, ChannelSigner, SignerProvider, NodeSigner, Reci
4242
use crate::events::ClosureReason;
4343
use crate::routing::gossip::NodeId;
4444
use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
45-
use crate::util::logger::Logger;
45+
use crate::util::logger::{Logger, WithContext};
4646
use crate::util::errors::APIError;
4747
use crate::util::config::{UserConfig, ChannelConfig, LegacyChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits, MaxDustHTLCExposure};
4848
use crate::util::scid_utils::scid_from_parts;
@@ -6463,6 +6463,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
64636463
F::Target: FeeEstimator,
64646464
L::Target: Logger,
64656465
{
6466+
let logger = WithContext::from(logger, Some(counterparty_node_id), Some(msg.temporary_channel_id));
64666467
let announced_channel = if (msg.channel_flags & 1) == 1 { true } else { false };
64676468

64686469
// First check the channel type is known, failing before we do anything else if we don't
@@ -6529,7 +6530,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
65296530
if msg.htlc_minimum_msat >= full_channel_value_msat {
65306531
return Err(ChannelError::Close(format!("Minimum htlc value ({}) was larger than full channel value ({})", msg.htlc_minimum_msat, full_channel_value_msat)));
65316532
}
6532-
Channel::<SP>::check_remote_fee(&channel_type, fee_estimator, msg.feerate_per_kw, None, logger)?;
6533+
Channel::<SP>::check_remote_fee(&channel_type, fee_estimator, msg.feerate_per_kw, None, &&logger)?;
65336534

65346535
let max_counterparty_selected_contest_delay = u16::min(config.channel_handshake_limits.their_to_self_delay, MAX_LOCAL_BREAKDOWN_TIMEOUT);
65356536
if msg.to_self_delay > max_counterparty_selected_contest_delay {

lightning/src/util/logger.rs

+72-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use bitcoin::secp256k1::PublicKey;
1818

1919
use core::cmp;
2020
use core::fmt;
21+
use core::ops::Deref;
2122

2223
use crate::ln::ChannelId;
2324
#[cfg(c_bindings)]
@@ -152,6 +153,39 @@ pub trait Logger {
152153
fn log(&self, record: Record);
153154
}
154155

156+
/// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`].
157+
pub struct WithContext<'a, L: Deref> where L::Target: Logger {
158+
/// The logger to delegate to after adding context to the record.
159+
logger: &'a L,
160+
/// The node id of the peer pertaining to the logged record.
161+
peer_id: Option<PublicKey>,
162+
/// The channel id of the channel pertaining to the logged record.
163+
channel_id: Option<ChannelId>,
164+
}
165+
166+
impl<'a, L: Deref> Logger for WithContext<'a, L> where L::Target: Logger {
167+
fn log(&self, mut record: Record) {
168+
if self.peer_id.is_some() {
169+
record.peer_id = self.peer_id
170+
};
171+
if self.channel_id.is_some() {
172+
record.channel_id = self.channel_id;
173+
}
174+
self.logger.log(record)
175+
}
176+
}
177+
178+
impl<'a, L: Deref> WithContext<'a, L> where L::Target: Logger {
179+
/// Wraps the given logger, providing additional context to any logged records.
180+
pub fn from(logger: &'a L, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>) -> Self {
181+
WithContext {
182+
logger,
183+
peer_id,
184+
channel_id,
185+
}
186+
}
187+
}
188+
155189
/// Wrapper for logging a [`PublicKey`] in hex format.
156190
///
157191
/// This is not exported to bindings users as fmt can't be used in C
@@ -202,7 +236,9 @@ impl<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone> fmt::Display fo
202236

203237
#[cfg(test)]
204238
mod tests {
205-
use crate::util::logger::{Logger, Level};
239+
use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
240+
use crate::ln::ChannelId;
241+
use crate::util::logger::{Logger, Level, WithContext};
206242
use crate::util::test_utils::TestLogger;
207243
use crate::sync::Arc;
208244

@@ -243,6 +279,41 @@ mod tests {
243279
wrapper.call_macros();
244280
}
245281

282+
#[test]
283+
fn test_logging_with_context() {
284+
let logger = &TestLogger::new();
285+
let secp_ctx = Secp256k1::new();
286+
let pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
287+
let context_logger = WithContext::from(&logger, Some(pk), Some(ChannelId([0; 32])));
288+
log_error!(context_logger, "This is an error");
289+
log_warn!(context_logger, "This is an error");
290+
log_debug!(context_logger, "This is an error");
291+
log_trace!(context_logger, "This is an error");
292+
log_gossip!(context_logger, "This is an error");
293+
log_info!(context_logger, "This is an error");
294+
logger.assert_log_context_contains(
295+
"lightning::util::logger::tests", Some(pk), Some(ChannelId([0;32])), 6
296+
);
297+
}
298+
299+
#[test]
300+
fn test_logging_with_multiple_wrapped_context() {
301+
let logger = &TestLogger::new();
302+
let secp_ctx = Secp256k1::new();
303+
let pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
304+
let context_logger = &WithContext::from(&logger, None, Some(ChannelId([0; 32])));
305+
let full_context_logger = WithContext::from(&context_logger, Some(pk), None);
306+
log_error!(full_context_logger, "This is an error");
307+
log_warn!(full_context_logger, "This is an error");
308+
log_debug!(full_context_logger, "This is an error");
309+
log_trace!(full_context_logger, "This is an error");
310+
log_gossip!(full_context_logger, "This is an error");
311+
log_info!(full_context_logger, "This is an error");
312+
logger.assert_log_context_contains(
313+
"lightning::util::logger::tests", Some(pk), Some(ChannelId([0;32])), 6
314+
);
315+
}
316+
246317
#[test]
247318
fn test_log_ordering() {
248319
assert!(Level::Error > Level::Warn);

lightning/src/util/test_utils.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -931,6 +931,7 @@ pub struct TestLogger {
931931
level: Level,
932932
pub(crate) id: String,
933933
pub lines: Mutex<HashMap<(String, String), usize>>,
934+
pub context: Mutex<HashMap<(String, Option<PublicKey>, Option<ChannelId>), usize>>,
934935
}
935936

936937
impl TestLogger {
@@ -941,7 +942,8 @@ impl TestLogger {
941942
TestLogger {
942943
level: Level::Trace,
943944
id,
944-
lines: Mutex::new(HashMap::new())
945+
lines: Mutex::new(HashMap::new()),
946+
context: Mutex::new(HashMap::new()),
945947
}
946948
}
947949
pub fn enable(&mut self, level: Level) {
@@ -976,11 +978,23 @@ impl TestLogger {
976978
}).map(|(_, c) | { c }).sum();
977979
assert_eq!(l, count)
978980
}
981+
982+
pub fn assert_log_context_contains(
983+
&self, module: &str, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>, count: usize
984+
) {
985+
let context_entries = self.context.lock().unwrap();
986+
let l: usize = context_entries.iter()
987+
.filter(|&(&(ref m, ref p, ref c), _)| m == module && *p == peer_id && *c == channel_id)
988+
.map(|(_, c) | c)
989+
.sum();
990+
assert_eq!(l, count)
991+
}
979992
}
980993

981994
impl Logger for TestLogger {
982995
fn log(&self, record: Record) {
983996
*self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
997+
*self.context.lock().unwrap().entry((record.module_path.to_string(), record.peer_id, record.channel_id)).or_insert(0) += 1;
984998
if record.level >= self.level {
985999
#[cfg(all(not(ldk_bench), feature = "std"))] {
9861000
let pfx = format!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line);

0 commit comments

Comments
 (0)