Skip to content

Commit 6b43153

Browse files
authored
Merge pull request #2314 from henghonglee/issue-2292
Add peer_id and channel_id explicitly to log records
2 parents 74bc9e2 + e21a500 commit 6b43153

File tree

17 files changed

+574
-270
lines changed

17 files changed

+574
-270
lines changed

fuzz/src/full_stack.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -728,7 +728,7 @@ mod tests {
728728
pub lines: Mutex<HashMap<(String, String), usize>>,
729729
}
730730
impl Logger for TrackingLogger {
731-
fn log(&self, record: &Record) {
731+
fn log(&self, record: Record) {
732732
*self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
733733
println!("{:<5} [{} : {}, {}] {}", record.level.to_string(), record.module_path, record.file, record.line, record.args);
734734
}

fuzz/src/onion_message.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ mod tests {
218218
pub lines: Mutex<HashMap<(String, String), usize>>,
219219
}
220220
impl Logger for TrackingLogger {
221-
fn log(&self, record: &Record) {
221+
fn log(&self, record: Record) {
222222
*self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
223223
println!("{:<5} [{} : {}, {}] {}", record.level.to_string(), record.module_path, record.file, record.line, record.args);
224224
}

fuzz/src/utils/test_logger.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ impl<'a, Out: Output> Write for LockedWriteAdapter<'a, Out> {
5656
}
5757

5858
impl<Out: Output> Logger for TestLogger<Out> {
59-
fn log(&self, record: &Record) {
59+
fn log(&self, record: Record) {
6060
write!(LockedWriteAdapter(&self.out),
6161
"{:<5} {} [{} : {}] {}\n", record.level.to_string(), self.id, record.module_path, record.line, record.args)
6262
.unwrap();

lightning-invoice/src/utils.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use lightning::ln::channelmanager::{PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA};
1414
use lightning::ln::inbound_payment::{create, create_from_hash, ExpandedKey};
1515
use lightning::routing::gossip::RoutingFees;
1616
use lightning::routing::router::{RouteHint, RouteHintHop, Router};
17-
use lightning::util::logger::Logger;
17+
use lightning::util::logger::{Logger, Record};
1818
use secp256k1::PublicKey;
1919
use core::ops::Deref;
2020
use core::time::Duration;
@@ -626,6 +626,7 @@ where
626626

627627
log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
628628
for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
629+
let logger = WithChannelDetails::from(logger, &channel);
629630
if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
630631
log_trace!(logger, "Ignoring channel {} for invoice route hints", &channel.channel_id);
631632
continue;
@@ -710,6 +711,7 @@ where
710711
.into_iter()
711712
.map(|(_, channel)| channel)
712713
.filter(|channel| {
714+
let logger = WithChannelDetails::from(logger, &channel);
713715
let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
714716
let include_channel = if has_pub_unconf_chan {
715717
// If we have a public channel, but it doesn't have enough confirmations to (yet)
@@ -790,6 +792,28 @@ fn prefer_current_channel(min_inbound_capacity_msat: Option<u64>, current_channe
790792
current_channel > candidate_channel
791793
}
792794

795+
/// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`].
796+
struct WithChannelDetails<'a, 'b, L: Deref> where L::Target: Logger {
797+
/// The logger to delegate to after adding context to the record.
798+
logger: &'a L,
799+
/// The [`ChannelDetails`] for adding relevant context to the logged record.
800+
details: &'b ChannelDetails
801+
}
802+
803+
impl<'a, 'b, L: Deref> Logger for WithChannelDetails<'a, 'b, L> where L::Target: Logger {
804+
fn log(&self, mut record: Record) {
805+
record.peer_id = Some(self.details.counterparty.node_id);
806+
record.channel_id = Some(self.details.channel_id);
807+
self.logger.log(record)
808+
}
809+
}
810+
811+
impl<'a, 'b, L: Deref> WithChannelDetails<'a, 'b, L> where L::Target: Logger {
812+
fn from(logger: &'a L, details: &'b ChannelDetails) -> Self {
813+
Self { logger, details }
814+
}
815+
}
816+
793817
#[cfg(test)]
794818
mod test {
795819
use core::cell::RefCell;

lightning-net-tokio/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -571,7 +571,7 @@ mod tests {
571571

572572
pub struct TestLogger();
573573
impl lightning::util::logger::Logger for TestLogger {
574-
fn log(&self, record: &lightning::util::logger::Record) {
574+
fn log(&self, record: lightning::util::logger::Record) {
575575
println!("{:<5} [{} : {}, {}] {}", record.level.to_string(), record.module_path, record.file, record.line, record.args);
576576
}
577577
}

lightning-rapid-gossip-sync/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
//! # use lightning::util::logger::{Logger, Record};
5050
//! # struct FakeLogger {}
5151
//! # impl Logger for FakeLogger {
52-
//! # fn log(&self, record: &Record) { }
52+
//! # fn log(&self, record: Record) { }
5353
//! # }
5454
//! # let logger = FakeLogger {};
5555
//!

lightning/src/chain/chainmonitor.rs

+44-35
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use bitcoin::hash_types::{Txid, BlockHash};
2929
use crate::chain;
3030
use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
3131
use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
32-
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, LATENCY_GRACE_PERIOD_BLOCKS};
32+
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, WithChannelMonitor, LATENCY_GRACE_PERIOD_BLOCKS};
3333
use crate::chain::transaction::{OutPoint, TransactionData};
3434
use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
3535
use crate::events;
@@ -359,6 +359,7 @@ where C::Target: chain::Filter,
359359
process: FN, funding_outpoint: &OutPoint, monitor_state: &MonitorHolder<ChannelSigner>
360360
) -> Result<(), ()> where FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs> {
361361
let monitor = &monitor_state.monitor;
362+
let logger = WithChannelMonitor::from(&self.logger, &monitor);
362363
let mut txn_outputs;
363364
{
364365
txn_outputs = process(monitor, txdata);
@@ -375,12 +376,12 @@ where C::Target: chain::Filter,
375376
}
376377
}
377378

378-
log_trace!(self.logger, "Syncing Channel Monitor for channel {}", log_funding_info!(monitor));
379+
log_trace!(logger, "Syncing Channel Monitor for channel {}", log_funding_info!(monitor));
379380
match self.persister.update_persisted_channel(*funding_outpoint, None, monitor, update_id) {
380381
ChannelMonitorUpdateStatus::Completed =>
381-
log_trace!(self.logger, "Finished syncing Channel Monitor for channel {}", log_funding_info!(monitor)),
382+
log_trace!(logger, "Finished syncing Channel Monitor for channel {}", log_funding_info!(monitor)),
382383
ChannelMonitorUpdateStatus::InProgress => {
383-
log_debug!(self.logger, "Channel Monitor sync for channel {} in progress, holding events until completion!", log_funding_info!(monitor));
384+
log_debug!(logger, "Channel Monitor sync for channel {} in progress, holding events until completion!", log_funding_info!(monitor));
384385
pending_monitor_updates.push(update_id);
385386
},
386387
ChannelMonitorUpdateStatus::UnrecoverableError => {
@@ -619,8 +620,9 @@ where C::Target: chain::Filter,
619620
pub fn rebroadcast_pending_claims(&self) {
620621
let monitors = self.monitors.read().unwrap();
621622
for (_, monitor_holder) in &*monitors {
623+
let logger = WithChannelMonitor::from(&self.logger, &monitor_holder.monitor);
622624
monitor_holder.monitor.rebroadcast_pending_claims(
623-
&*self.broadcaster, &*self.fee_estimator, &*self.logger
625+
&*self.broadcaster, &*self.fee_estimator, &logger
624626
)
625627
}
626628
}
@@ -638,17 +640,19 @@ where
638640
fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
639641
log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height);
640642
self.process_chain_data(header, Some(height), &txdata, |monitor, txdata| {
643+
let logger = WithChannelMonitor::from(&self.logger, &monitor);
641644
monitor.block_connected(
642-
header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
645+
header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &logger)
643646
});
644647
}
645648

646649
fn block_disconnected(&self, header: &Header, height: u32) {
647650
let monitor_states = self.monitors.read().unwrap();
648651
log_debug!(self.logger, "Latest block {} at height {} removed via block_disconnected", header.block_hash(), height);
649652
for monitor_state in monitor_states.values() {
653+
let logger = WithChannelMonitor::from(&self.logger, &monitor_state.monitor);
650654
monitor_state.monitor.block_disconnected(
651-
header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
655+
header, height, &*self.broadcaster, &*self.fee_estimator, &logger);
652656
}
653657
}
654658
}
@@ -665,27 +669,30 @@ where
665669
fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
666670
log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash());
667671
self.process_chain_data(header, None, txdata, |monitor, txdata| {
672+
let logger = WithChannelMonitor::from(&self.logger, &monitor);
668673
monitor.transactions_confirmed(
669-
header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
674+
header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &logger)
670675
});
671676
}
672677

673678
fn transaction_unconfirmed(&self, txid: &Txid) {
674679
log_debug!(self.logger, "Transaction {} reorganized out of chain", txid);
675680
let monitor_states = self.monitors.read().unwrap();
676681
for monitor_state in monitor_states.values() {
677-
monitor_state.monitor.transaction_unconfirmed(txid, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
682+
let logger = WithChannelMonitor::from(&self.logger, &monitor_state.monitor);
683+
monitor_state.monitor.transaction_unconfirmed(txid, &*self.broadcaster, &*self.fee_estimator, &logger);
678684
}
679685
}
680686

681687
fn best_block_updated(&self, header: &Header, height: u32) {
682688
log_debug!(self.logger, "New best block {} at height {} provided via best_block_updated", header.block_hash(), height);
683689
self.process_chain_data(header, Some(height), &[], |monitor, txdata| {
690+
let logger = WithChannelMonitor::from(&self.logger, &monitor);
684691
// While in practice there shouldn't be any recursive calls when given empty txdata,
685692
// it's still possible if a chain::Filter implementation returns a transaction.
686693
debug_assert!(txdata.is_empty());
687694
monitor.best_block_updated(
688-
header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
695+
header, height, &*self.broadcaster, &*self.fee_estimator, &logger)
689696
});
690697
}
691698

@@ -711,29 +718,30 @@ where C::Target: chain::Filter,
711718
P::Target: Persist<ChannelSigner>,
712719
{
713720
fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<ChannelMonitorUpdateStatus, ()> {
721+
let logger = WithChannelMonitor::from(&self.logger, &monitor);
714722
let mut monitors = self.monitors.write().unwrap();
715723
let entry = match monitors.entry(funding_outpoint) {
716724
hash_map::Entry::Occupied(_) => {
717-
log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
725+
log_error!(logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
718726
return Err(());
719727
},
720728
hash_map::Entry::Vacant(e) => e,
721729
};
722-
log_trace!(self.logger, "Got new ChannelMonitor for channel {}", log_funding_info!(monitor));
730+
log_trace!(logger, "Got new ChannelMonitor for channel {}", log_funding_info!(monitor));
723731
let update_id = MonitorUpdateId::from_new_monitor(&monitor);
724732
let mut pending_monitor_updates = Vec::new();
725733
let persist_res = self.persister.persist_new_channel(funding_outpoint, &monitor, update_id);
726734
match persist_res {
727735
ChannelMonitorUpdateStatus::InProgress => {
728-
log_info!(self.logger, "Persistence of new ChannelMonitor for channel {} in progress", log_funding_info!(monitor));
736+
log_info!(logger, "Persistence of new ChannelMonitor for channel {} in progress", log_funding_info!(monitor));
729737
pending_monitor_updates.push(update_id);
730738
},
731739
ChannelMonitorUpdateStatus::Completed => {
732-
log_info!(self.logger, "Persistence of new ChannelMonitor for channel {} completed", log_funding_info!(monitor));
740+
log_info!(logger, "Persistence of new ChannelMonitor for channel {} completed", log_funding_info!(monitor));
733741
},
734742
ChannelMonitorUpdateStatus::UnrecoverableError => {
735743
let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
736-
log_error!(self.logger, "{}", err_str);
744+
log_error!(logger, "{}", err_str);
737745
panic!("{}", err_str);
738746
},
739747
}
@@ -750,8 +758,9 @@ where C::Target: chain::Filter,
750758

751759
fn update_channel(&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus {
752760
// Update the monitor that watches the channel referred to by the given outpoint.
753-
let monitors = self.monitors.read().unwrap();
754-
let ret = match monitors.get(&funding_txo) {
761+
let monitors_lock = self.monitors.read().unwrap();
762+
let monitors = monitors_lock.deref();
763+
match monitors.get(&funding_txo) {
755764
None => {
756765
log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
757766

@@ -765,7 +774,8 @@ where C::Target: chain::Filter,
765774
},
766775
Some(monitor_state) => {
767776
let monitor = &monitor_state.monitor;
768-
log_trace!(self.logger, "Updating ChannelMonitor for channel {}", log_funding_info!(monitor));
777+
let logger = WithChannelMonitor::from(&self.logger, &monitor);
778+
log_trace!(logger, "Updating ChannelMonitor for channel {}", log_funding_info!(monitor));
769779
let update_res = monitor.update_monitor(update, &self.broadcaster, &self.fee_estimator, &self.logger);
770780

771781
let update_id = MonitorUpdateId::from_monitor_update(update);
@@ -776,49 +786,48 @@ where C::Target: chain::Filter,
776786
// We don't want to persist a `monitor_update` which results in a failure to apply later
777787
// while reading `channel_monitor` with updates from storage. Instead, we should persist
778788
// the entire `channel_monitor` here.
779-
log_warn!(self.logger, "Failed to update ChannelMonitor for channel {}. Going ahead and persisting the entire ChannelMonitor", log_funding_info!(monitor));
789+
log_warn!(logger, "Failed to update ChannelMonitor for channel {}. Going ahead and persisting the entire ChannelMonitor", log_funding_info!(monitor));
780790
self.persister.update_persisted_channel(funding_txo, None, monitor, update_id)
781791
} else {
782792
self.persister.update_persisted_channel(funding_txo, Some(update), monitor, update_id)
783793
};
784794
match persist_res {
785795
ChannelMonitorUpdateStatus::InProgress => {
786796
pending_monitor_updates.push(update_id);
787-
log_debug!(self.logger, "Persistence of ChannelMonitorUpdate for channel {} in progress", log_funding_info!(monitor));
797+
log_debug!(logger, "Persistence of ChannelMonitorUpdate for channel {} in progress", log_funding_info!(monitor));
788798
},
789799
ChannelMonitorUpdateStatus::Completed => {
790-
log_debug!(self.logger, "Persistence of ChannelMonitorUpdate for channel {} completed", log_funding_info!(monitor));
800+
log_debug!(logger, "Persistence of ChannelMonitorUpdate for channel {} completed", log_funding_info!(monitor));
801+
},
802+
ChannelMonitorUpdateStatus::UnrecoverableError => {
803+
// Take the monitors lock for writing so that we poison it and any future
804+
// operations going forward fail immediately.
805+
core::mem::drop(monitors);
806+
let _poison = self.monitors.write().unwrap();
807+
let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
808+
log_error!(logger, "{}", err_str);
809+
panic!("{}", err_str);
791810
},
792-
ChannelMonitorUpdateStatus::UnrecoverableError => { /* we'll panic in a moment */ },
793811
}
794812
if update_res.is_err() {
795813
ChannelMonitorUpdateStatus::InProgress
796814
} else {
797815
persist_res
798816
}
799817
}
800-
};
801-
if let ChannelMonitorUpdateStatus::UnrecoverableError = ret {
802-
// Take the monitors lock for writing so that we poison it and any future
803-
// operations going forward fail immediately.
804-
core::mem::drop(monitors);
805-
let _poison = self.monitors.write().unwrap();
806-
let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
807-
log_error!(self.logger, "{}", err_str);
808-
panic!("{}", err_str);
809818
}
810-
ret
811819
}
812820

813821
fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
814822
let mut pending_monitor_events = self.pending_monitor_events.lock().unwrap().split_off(0);
815823
for monitor_state in self.monitors.read().unwrap().values() {
824+
let logger = WithChannelMonitor::from(&self.logger, &monitor_state.monitor);
816825
let is_pending_monitor_update = monitor_state.has_pending_chainsync_updates(&monitor_state.pending_monitor_updates.lock().unwrap());
817826
if !is_pending_monitor_update || monitor_state.last_chain_persist_height.load(Ordering::Acquire) + LATENCY_GRACE_PERIOD_BLOCKS as usize <= self.highest_chain_height.load(Ordering::Acquire) {
818827
if is_pending_monitor_update {
819-
log_error!(self.logger, "A ChannelMonitor sync took longer than {} blocks to complete.", LATENCY_GRACE_PERIOD_BLOCKS);
820-
log_error!(self.logger, " To avoid funds-loss, we are allowing monitor updates to be released.");
821-
log_error!(self.logger, " This may cause duplicate payment events to be generated.");
828+
log_error!(logger, "A ChannelMonitor sync took longer than {} blocks to complete.", LATENCY_GRACE_PERIOD_BLOCKS);
829+
log_error!(logger, " To avoid funds-loss, we are allowing monitor updates to be released.");
830+
log_error!(logger, " This may cause duplicate payment events to be generated.");
822831
}
823832
let monitor_events = monitor_state.monitor.get_and_clear_pending_monitor_events();
824833
if monitor_events.len() > 0 {

0 commit comments

Comments
 (0)