|
15 | 15 |
|
16 | 16 | use bitcoin::secp256k1::PublicKey; |
17 | 17 |
|
| 18 | +use core::cell::RefCell; |
18 | 19 | use core::cmp; |
19 | 20 | use core::fmt; |
20 | 21 | use core::ops::Deref; |
@@ -261,15 +262,60 @@ impl<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone> fmt::Display fo |
261 | 262 | } |
262 | 263 | } |
263 | 264 |
|
| 265 | +thread_local! { |
| 266 | + pub(crate) static TLS_LOGGER: RefCell<Option<&'static dyn Logger>> = RefCell::new(None); |
| 267 | +} |
| 268 | + |
| 269 | +pub struct LoggerScope<'a> { |
| 270 | + _marker: std::marker::PhantomData<&'a ()>, |
| 271 | +} |
| 272 | + |
| 273 | +impl<'a> LoggerScope<'a> { |
| 274 | + pub fn new<L: Logger + 'a>(logger: &'a L) -> Self { |
| 275 | + TLS_LOGGER.with(|cell| { |
| 276 | + let mut borrow = cell.borrow_mut(); |
| 277 | + |
| 278 | + // Prevent nested scopes |
| 279 | + if borrow.is_some() { |
| 280 | + panic!("LoggerScope already active in this thread"); |
| 281 | + } |
| 282 | + |
| 283 | + // Transmute is safe in practice because the RAII pattern ensures: |
| 284 | + // - The TLS logger reference is only used while the guard exists. |
| 285 | + // - The guard cannot outlive the logger (thanks to PhantomData<'a>). |
| 286 | + let logger_ref: &dyn Logger = logger; |
| 287 | + let logger_ref_static: &'static dyn Logger = unsafe { std::mem::transmute(logger_ref) }; |
| 288 | + |
| 289 | + *borrow = Some(logger_ref_static); |
| 290 | + }); |
| 291 | + LoggerScope { _marker: std::marker::PhantomData } |
| 292 | + } |
| 293 | +} |
| 294 | + |
| 295 | +impl<'a> Drop for LoggerScope<'a> { |
| 296 | + fn drop(&mut self) { |
| 297 | + TLS_LOGGER.with(|cell| { |
| 298 | + *cell.borrow_mut() = None; |
| 299 | + }); |
| 300 | + } |
| 301 | +} |
| 302 | + |
264 | 303 | #[cfg(test)] |
265 | 304 | mod tests { |
266 | 305 | use crate::ln::types::ChannelId; |
267 | 306 | use crate::sync::Arc; |
268 | 307 | use crate::types::payment::PaymentHash; |
269 | | - use crate::util::logger::{Level, Logger, WithContext}; |
| 308 | + use crate::util::logger::{Level, Logger, LoggerScope, WithContext}; |
270 | 309 | use crate::util::test_utils::TestLogger; |
271 | 310 | use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; |
272 | 311 |
|
| 312 | + #[test] |
| 313 | + fn logger_scope() { |
| 314 | + let logger = TestLogger::new(); |
| 315 | + let _scope = LoggerScope::new(&logger); |
| 316 | + log_info_tls!("Info") |
| 317 | + } |
| 318 | + |
273 | 319 | #[test] |
274 | 320 | fn test_level_show() { |
275 | 321 | assert_eq!("INFO", Level::Info.to_string()); |
|
0 commit comments