Allow logging to specify an explicit log level instead of a macro
[rust-lightning] / lightning / src / util / macro_logger.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 use chain::transaction::OutPoint;
11 use chain::keysinterface::SpendableOutputDescriptor;
12
13 use bitcoin::hash_types::Txid;
14 use bitcoin::blockdata::transaction::Transaction;
15 use bitcoin::secp256k1::key::PublicKey;
16
17 use routing::router::Route;
18 use ln::chan_utils::HTLCType;
19
20 pub(crate) struct DebugPubKey<'a>(pub &'a PublicKey);
21 impl<'a> core::fmt::Display for DebugPubKey<'a> {
22         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
23                 for i in self.0.serialize().iter() {
24                         write!(f, "{:02x}", i)?;
25                 }
26                 Ok(())
27         }
28 }
29 macro_rules! log_pubkey {
30         ($obj: expr) => {
31                 ::util::macro_logger::DebugPubKey(&$obj)
32         }
33 }
34
35 pub(crate) struct DebugBytes<'a>(pub &'a [u8]);
36 impl<'a> core::fmt::Display for DebugBytes<'a> {
37         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
38                 for i in self.0 {
39                         write!(f, "{:02x}", i)?;
40                 }
41                 Ok(())
42         }
43 }
44 macro_rules! log_bytes {
45         ($obj: expr) => {
46                 ::util::macro_logger::DebugBytes(&$obj)
47         }
48 }
49
50 pub(crate) struct DebugFundingChannelId<'a>(pub &'a Txid, pub u16);
51 impl<'a> core::fmt::Display for DebugFundingChannelId<'a> {
52         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
53                 for i in (OutPoint { txid: self.0.clone(), index: self.1 }).to_channel_id().iter() {
54                         write!(f, "{:02x}", i)?;
55                 }
56                 Ok(())
57         }
58 }
59 macro_rules! log_funding_channel_id {
60         ($funding_txid: expr, $funding_txo: expr) => {
61                 ::util::macro_logger::DebugFundingChannelId(&$funding_txid, $funding_txo)
62         }
63 }
64
65 pub(crate) struct DebugFundingInfo<'a, T: 'a>(pub &'a (OutPoint, T));
66 impl<'a, T> core::fmt::Display for DebugFundingInfo<'a, T> {
67         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
68                 DebugBytes(&(self.0).0.to_channel_id()[..]).fmt(f)
69         }
70 }
71 macro_rules! log_funding_info {
72         ($key_storage: expr) => {
73                 ::util::macro_logger::DebugFundingInfo(&$key_storage.get_funding_txo())
74         }
75 }
76
77 pub(crate) struct DebugRoute<'a>(pub &'a Route);
78 impl<'a> core::fmt::Display for DebugRoute<'a> {
79         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
80                 for (idx, p) in self.0.paths.iter().enumerate() {
81                         writeln!(f, "path {}:", idx)?;
82                         for h in p.iter() {
83                                 writeln!(f, " node_id: {}, short_channel_id: {}, fee_msat: {}, cltv_expiry_delta: {}", log_pubkey!(h.pubkey), h.short_channel_id, h.fee_msat, h.cltv_expiry_delta)?;
84                         }
85                 }
86                 Ok(())
87         }
88 }
89 macro_rules! log_route {
90         ($obj: expr) => {
91                 ::util::macro_logger::DebugRoute(&$obj)
92         }
93 }
94
95 pub(crate) struct DebugTx<'a>(pub &'a Transaction);
96 impl<'a> core::fmt::Display for DebugTx<'a> {
97         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
98                 if self.0.input.len() >= 1 && self.0.input.iter().any(|i| !i.witness.is_empty()) {
99                         if self.0.input.len() == 1 && self.0.input[0].witness.last().unwrap().len() == 71 &&
100                                         (self.0.input[0].sequence >> 8*3) as u8 == 0x80 {
101                                 write!(f, "commitment tx ")?;
102                         } else if self.0.input.len() == 1 && self.0.input[0].witness.last().unwrap().len() == 71 {
103                                 write!(f, "closing tx ")?;
104                         } else if self.0.input.len() == 1 && HTLCType::scriptlen_to_htlctype(self.0.input[0].witness.last().unwrap().len()) == Some(HTLCType::OfferedHTLC) &&
105                                         self.0.input[0].witness.len() == 5 {
106                                 write!(f, "HTLC-timeout tx ")?;
107                         } else if self.0.input.len() == 1 && HTLCType::scriptlen_to_htlctype(self.0.input[0].witness.last().unwrap().len()) == Some(HTLCType::AcceptedHTLC) &&
108                                         self.0.input[0].witness.len() == 5 {
109                                 write!(f, "HTLC-success tx ")?;
110                         } else {
111                                 for inp in &self.0.input {
112                                         if !inp.witness.is_empty() {
113                                                 if HTLCType::scriptlen_to_htlctype(inp.witness.last().unwrap().len()) == Some(HTLCType::OfferedHTLC) { write!(f, "preimage-")?; break }
114                                                 else if HTLCType::scriptlen_to_htlctype(inp.witness.last().unwrap().len()) == Some(HTLCType::AcceptedHTLC) { write!(f, "timeout-")?; break }
115                                         }
116                                 }
117                                 write!(f, "tx ")?;
118                         }
119                 } else {
120                         debug_assert!(false, "We should never generate unknown transaction types");
121                         write!(f, "unknown tx type ").unwrap();
122                 }
123                 write!(f, "with txid {}", self.0.txid())?;
124                 Ok(())
125         }
126 }
127
128 macro_rules! log_tx {
129         ($obj: expr) => {
130                 ::util::macro_logger::DebugTx(&$obj)
131         }
132 }
133
134 pub(crate) struct DebugSpendable<'a>(pub &'a SpendableOutputDescriptor);
135 impl<'a> core::fmt::Display for DebugSpendable<'a> {
136         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
137                 match self.0 {
138                         &SpendableOutputDescriptor::StaticOutput { ref outpoint, .. } => {
139                                 write!(f, "StaticOutput {}:{} marked for spending", outpoint.txid, outpoint.index)?;
140                         }
141                         &SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) => {
142                                 write!(f, "DelayedPaymentOutput {}:{} marked for spending", descriptor.outpoint.txid, descriptor.outpoint.index)?;
143                         }
144                         &SpendableOutputDescriptor::StaticPaymentOutput(ref descriptor) => {
145                                 write!(f, "DynamicOutputP2WPKH {}:{} marked for spending", descriptor.outpoint.txid, descriptor.outpoint.index)?;
146                         }
147                 }
148                 Ok(())
149         }
150 }
151
152 macro_rules! log_spendable {
153         ($obj: expr) => {
154                 ::util::macro_logger::DebugSpendable(&$obj)
155         }
156 }
157
158 /// Create a new Record and log it. You probably don't want to use this macro directly,
159 /// but it needs to be exported so `log_trace` etc can use it in external crates.
160 #[macro_export]
161 macro_rules! log_internal {
162         ($logger: expr, $lvl:expr, $($arg:tt)+) => (
163                 $logger.log(&$crate::util::logger::Record::new($lvl, format_args!($($arg)+), module_path!(), file!(), line!()));
164         );
165 }
166
167 /// Logs an entry at the given level.
168 #[macro_export]
169 macro_rules! log_given_level {
170         ($logger: expr, $lvl:expr, $($arg:tt)+) => (
171                 match $lvl {
172                         #[cfg(not(any(feature = "max_level_off")))]
173                         $crate::util::logger::Level::Error => log_internal!($logger, $lvl, $($arg)*),
174                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error")))]
175                         $crate::util::logger::Level::Warn => log_internal!($logger, $lvl, $($arg)*),
176                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn")))]
177                         $crate::util::logger::Level::Info => log_internal!($logger, $lvl, $($arg)*),
178                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info")))]
179                         $crate::util::logger::Level::Debug => log_internal!($logger, $lvl, $($arg)*),
180                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug")))]
181                         $crate::util::logger::Level::Trace => log_internal!($logger, $lvl, $($arg)*),
182
183                         #[cfg(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug"))]
184                         _ => {
185                                 // The level is disabled at compile-time
186                         },
187                 }
188         );
189 }
190
191 /// Log an error.
192 #[macro_export]
193 macro_rules! log_error {
194         ($logger: expr, $($arg:tt)*) => (
195                 log_given_level!($logger, $crate::util::logger::Level::Error, $($arg)*);
196         )
197 }
198
199 macro_rules! log_warn {
200         ($logger: expr, $($arg:tt)*) => (
201                 log_given_level!($logger, $crate::util::logger::Level::Warn, $($arg)*);
202         )
203 }
204
205 macro_rules! log_info {
206         ($logger: expr, $($arg:tt)*) => (
207                 log_given_level!($logger, $crate::util::logger::Level::Info, $($arg)*);
208         )
209 }
210
211 macro_rules! log_debug {
212         ($logger: expr, $($arg:tt)*) => (
213                 log_given_level!($logger, $crate::util::logger::Level::Debug, $($arg)*);
214         )
215 }
216
217 /// Log a trace log.
218 #[macro_export]
219 macro_rules! log_trace {
220         ($logger: expr, $($arg:tt)*) => (
221                 log_given_level!($logger, $crate::util::logger::Level::Trace, $($arg)*);
222         )
223 }