Skip to content

Commit 99f4840

Browse files
committed
[add] macros for utilizing the global logger packaged with the logging crate.
1 parent cf2d3ce commit 99f4840

File tree

3 files changed

+87
-25
lines changed

3 files changed

+87
-25
lines changed

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Log handling implementations for the logger.
22
33
use std::{
4+
fmt::Debug,
45
fs::OpenOptions,
56
io::Write,
67
time::SystemTime,
@@ -18,6 +19,8 @@ pub trait Handler {
1819
}
1920

2021
/// A handler that logs to a file.
22+
23+
#[derive(Debug, Clone, PartialEq, PartialOrd)]
2124
pub struct FileHandler {
2225
file: String,
2326
log_buffer: Vec<String>,
@@ -98,13 +101,16 @@ impl Handler for FileHandler {
98101
}
99102
}
100103

104+
#[derive(Debug, Clone, PartialEq, PartialOrd)]
101105
pub struct ConsoleHandler {
102106
name: String,
103107
}
104108

105109
impl ConsoleHandler {
106-
pub fn new(name: String) -> Self {
107-
return Self { name };
110+
pub fn new(name: &str) -> Self {
111+
return Self {
112+
name: name.to_string(),
113+
};
108114
}
109115

110116
fn log(&mut self, log_level: LogLevel, message: String) {

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

Lines changed: 69 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,6 @@
11
//! A simple logging library for lambda-rs crates.
22
3-
use std::{
4-
fs::OpenOptions,
5-
io::Write,
6-
time::{
7-
SystemTime,
8-
UNIX_EPOCH,
9-
},
10-
};
3+
use std::fmt::Debug;
114

125
/// A trait for handling log messages.
136
pub mod handler;
@@ -31,14 +24,32 @@ pub struct Logger {
3124
}
3225

3326
impl Logger {
34-
pub fn new(level: LogLevel, name: String) -> Self {
27+
/// Creates a new logger with the given log level and name.
28+
pub fn new(level: LogLevel, name: &str) -> Self {
3529
Self {
36-
name,
30+
name: name.to_string(),
3731
level,
3832
handlers: Vec::new(),
3933
}
4034
}
4135

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");
51+
}
52+
4253
/// Adds a handler to the logger. Handlers are called in the order they
4354
/// are added.
4455
pub fn add_handler(&mut self, handler: Box<dyn handler::Handler>) {
@@ -114,3 +125,51 @@ impl Logger {
114125
std::process::exit(1);
115126
}
116127
}
128+
129+
static mut LOGGER: Option<Logger> = None;
130+
131+
/// Trace logging macro using the global logger instance.
132+
#[macro_export]
133+
macro_rules! trace {
134+
($($arg:tt)*) => {
135+
Logger::global().trace(format!("{}", format_args!($($arg)*)));
136+
};
137+
}
138+
139+
/// Trace logging macro using the global logger instance.
140+
#[macro_export]
141+
macro_rules! debug {
142+
($($arg:tt)*) => {
143+
Logger::global().debug(format!("{}", format_args!($($arg)*)));
144+
};
145+
}
146+
147+
/// Trace logging macro using the global logger instance.
148+
#[macro_export]
149+
macro_rules! info {
150+
($($arg:tt)*) => {
151+
Logger::global().info(format!("{}", format_args!($($arg)*)));
152+
};
153+
}
154+
155+
// Define logging macros that use the global logger instance
156+
#[macro_export]
157+
macro_rules! warn {
158+
($($arg:tt)*) => {
159+
Logger.global().warn(format!("{}", format_args!($($arg)*)));
160+
};
161+
}
162+
163+
#[macro_export]
164+
macro_rules! error {
165+
($($arg:tt)*) => {
166+
Logger::global().error(format!("{}", format_args!($($arg)*)));
167+
};
168+
}
169+
170+
#[macro_export]
171+
macro_rules! fatal {
172+
($($arg:tt)*) => {
173+
Logger::global().fatal(format!("{}", format_args!($($arg)*)));
174+
};
175+
}

crates/lambda-rs/src/runtimes/application.rs

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use lambda_platform::winit::{
1414
Loop,
1515
LoopBuilder,
1616
};
17+
#[macro_use]
1718
use logging::{
1819
handler::ConsoleHandler,
1920
Logger,
@@ -155,9 +156,6 @@ impl Runtime<(), String> for ApplicationRuntime {
155156
render_context,
156157
} = self;
157158

158-
let mut runtime_logger =
159-
Logger::new(logging::LogLevel::TRACE, name.clone());
160-
runtime_logger.add_handler(Box::new(ConsoleHandler::new(name.clone())));
161159
let mut active_render_context = Some(render_context);
162160

163161
let publisher = event_loop.create_event_publisher();
@@ -239,10 +237,9 @@ impl Runtime<(), String> for ApplicationRuntime {
239237
})
240238
}
241239
_ => {
242-
runtime_logger.warn(
243-
format!("[WARN] Unhandled synthetic keyboard event: {:?}",
244-
input)
245-
);
240+
logging::info!(
241+
"[INFO] Unhandled synthetic keyboard event: {:?}",
242+
input);
246243
None
247244
}
248245
},
@@ -352,7 +349,7 @@ impl Runtime<(), String> for ApplicationRuntime {
352349
WinitEvent::UserEvent(lambda_event) => match lambda_event {
353350
Events::Runtime { event, issued_at } => match event {
354351
RuntimeEvent::Initialized => {
355-
runtime_logger.info(format!("Initializing all of the components for the runtime: {}", name));
352+
logging::info!("Initializing all of the components for the runtime: {}", name);
356353
for component in &mut component_stack {
357354
component.on_attach(active_render_context.as_mut().unwrap());
358355
}
@@ -382,22 +379,22 @@ impl Runtime<(), String> for ApplicationRuntime {
382379
.destroy();
383380

384381

385-
runtime_logger.info(String::from("All resources were successfully deleted."));
382+
logging::info!("All resources were successfully deleted.");
386383
None
387384
}
388385
};
389386

390387
match mapped_event {
391388
Some(event) => {
392-
runtime_logger.trace(format!("Sending event: {:?} to all components", event));
389+
logging::trace!("Sending event: {:?} to all components", event);
393390

394391
for component in &mut component_stack {
395392
let event_result = component.on_event(event.clone());
396393
match event_result {
397394
Ok(_) => {}
398395
Err(e) => {
399396
let error = format!("[ERROR] A component has panicked while handling an event. {:?}", e);
400-
runtime_logger.error(error.clone());
397+
logging::error!("A component has panicked while handling an event. {:?}", e);
401398
publisher.publish_event(Events::Runtime{event: RuntimeEvent::ComponentPanic{ message: error}, issued_at: Instant::now()});
402399
}
403400
}
@@ -412,10 +409,10 @@ impl Runtime<(), String> for ApplicationRuntime {
412409
/// When an application runtime starts, it will attach all of the components that
413410
/// have been added during the construction phase in the users code.
414411
fn on_start(&mut self) {
415-
println!("[INFO] Starting the runtime {}", self.name);
412+
logging::info!("Starting the runtime: {}", self.name);
416413
}
417414

418415
fn on_stop(&mut self) {
419-
println!("[INFO] Stopping {}", self.name)
416+
logging::info!("Stopping the runtime: {}", self.name);
420417
}
421418
}

0 commit comments

Comments
 (0)