Skip to content

Commit 24f9fb2

Browse files
committed
Fix global logger initialization
1 parent 9d02f17 commit 24f9fb2

File tree

2 files changed

+18
-17
lines changed

2 files changed

+18
-17
lines changed

crates/lambda-rs-logging/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,6 @@ license = "MIT"
88
[lib]
99
name = "logging"
1010
path = "src/lib.rs"
11+
12+
[dependencies]
13+
once_cell = "1"

crates/lambda-rs-logging/src/lib.rs

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
//! A simple logging library for lambda-rs crates.
22
3-
use std::fmt::Debug;
3+
use std::{fmt::Debug, sync::{Mutex, MutexGuard}};
4+
5+
use once_cell::sync::Lazy;
46

57
/// A trait for handling log messages.
68
pub mod handler;
@@ -33,21 +35,10 @@ impl Logger {
3335
}
3436
}
3537

36-
/// Returns the global logger.
37-
pub fn global() -> &'static mut Self {
38-
// TODO(vmarcella): Fix the instantiation for the global logger.
39-
unsafe {
40-
if LOGGER.is_none() {
41-
LOGGER = Some(Logger {
42-
level: LogLevel::TRACE,
43-
name: "lambda-rs".to_string(),
44-
handlers: vec![Box::new(handler::ConsoleHandler::new("lambda-rs"))],
45-
});
46-
}
47-
};
48-
return unsafe { &mut LOGGER }
49-
.as_mut()
50-
.expect("Logger not initialized");
38+
/// Returns a handle to the global logger. The logger is lazily
39+
/// initialized on first access.
40+
pub fn global() -> MutexGuard<'static, Self> {
41+
LOGGER.lock().expect("Logger mutex poisoned")
5142
}
5243

5344
/// Adds a handler to the logger. Handlers are called in the order they
@@ -126,7 +117,14 @@ impl Logger {
126117
}
127118
}
128119

129-
pub(crate) static mut LOGGER: Option<Logger> = None;
120+
/// Global logger instance used by the logging macros.
121+
static LOGGER: Lazy<Mutex<Logger>> = Lazy::new(|| {
122+
Mutex::new(Logger {
123+
level: LogLevel::TRACE,
124+
name: "lambda-rs".to_string(),
125+
handlers: vec![Box::new(handler::ConsoleHandler::new("lambda-rs"))],
126+
})
127+
});
130128

131129
/// Trace logging macro using the global logger instance.
132130
#[macro_export]

0 commit comments

Comments
 (0)