From 24f9fb2caf82d41a160af45589b2f8decf4204bd Mon Sep 17 00:00:00 2001 From: Vincenzo Marcella <6026326+vmarcella@users.noreply.github.com> Date: Sun, 22 Jun 2025 14:31:09 -0700 Subject: [PATCH] Fix global logger initialization --- crates/lambda-rs-logging/Cargo.toml | 3 +++ crates/lambda-rs-logging/src/lib.rs | 32 ++++++++++++++--------------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/crates/lambda-rs-logging/Cargo.toml b/crates/lambda-rs-logging/Cargo.toml index 7c295a30..b245c946 100644 --- a/crates/lambda-rs-logging/Cargo.toml +++ b/crates/lambda-rs-logging/Cargo.toml @@ -8,3 +8,6 @@ license = "MIT" [lib] name = "logging" path = "src/lib.rs" + +[dependencies] +once_cell = "1" diff --git a/crates/lambda-rs-logging/src/lib.rs b/crates/lambda-rs-logging/src/lib.rs index 1fbd7cf6..a016ca7c 100644 --- a/crates/lambda-rs-logging/src/lib.rs +++ b/crates/lambda-rs-logging/src/lib.rs @@ -1,6 +1,8 @@ //! A simple logging library for lambda-rs crates. -use std::fmt::Debug; +use std::{fmt::Debug, sync::{Mutex, MutexGuard}}; + +use once_cell::sync::Lazy; /// A trait for handling log messages. pub mod handler; @@ -33,21 +35,10 @@ impl Logger { } } - /// Returns the global logger. - pub fn global() -> &'static mut Self { - // TODO(vmarcella): Fix the instantiation for the global logger. - unsafe { - if LOGGER.is_none() { - LOGGER = Some(Logger { - level: LogLevel::TRACE, - name: "lambda-rs".to_string(), - handlers: vec![Box::new(handler::ConsoleHandler::new("lambda-rs"))], - }); - } - }; - return unsafe { &mut LOGGER } - .as_mut() - .expect("Logger not initialized"); + /// Returns a handle to the global logger. The logger is lazily + /// initialized on first access. + pub fn global() -> MutexGuard<'static, Self> { + LOGGER.lock().expect("Logger mutex poisoned") } /// Adds a handler to the logger. Handlers are called in the order they @@ -126,7 +117,14 @@ impl Logger { } } -pub(crate) static mut LOGGER: Option = None; +/// Global logger instance used by the logging macros. +static LOGGER: Lazy> = Lazy::new(|| { + Mutex::new(Logger { + level: LogLevel::TRACE, + name: "lambda-rs".to_string(), + handlers: vec![Box::new(handler::ConsoleHandler::new("lambda-rs"))], + }) +}); /// Trace logging macro using the global logger instance. #[macro_export]