|
1 | 1 | //! A simple logging library for lambda-rs crates. |
2 | 2 |
|
3 | | -use std::fmt::Debug; |
| 3 | +use std::{fmt::Debug, sync::{Mutex, MutexGuard}}; |
| 4 | + |
| 5 | +use once_cell::sync::Lazy; |
4 | 6 |
|
5 | 7 | /// A trait for handling log messages. |
6 | 8 | pub mod handler; |
@@ -33,21 +35,10 @@ impl Logger { |
33 | 35 | } |
34 | 36 | } |
35 | 37 |
|
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") |
51 | 42 | } |
52 | 43 |
|
53 | 44 | /// Adds a handler to the logger. Handlers are called in the order they |
@@ -126,7 +117,14 @@ impl Logger { |
126 | 117 | } |
127 | 118 | } |
128 | 119 |
|
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 | +}); |
130 | 128 |
|
131 | 129 | /// Trace logging macro using the global logger instance. |
132 | 130 | #[macro_export] |
|
0 commit comments