Skip to content

Add initialization option for replacing the internal logger with the Rust log crate #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions raylib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ cfg-if = "1.0.0"
serde = { version = "1.0.125", features = ["derive"], optional = true }
serde_json = { version = "1.0.64", optional = true }
nalgebra = { version = "0.26", optional = true }
num-traits = "0.2.14"
printf = "0.1.0"
log = "0.4.14"
num-derive = "0.3.3"

[features]
nightly = []
Expand Down
47 changes: 47 additions & 0 deletions raylib/src/core/log_hooks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//! Contains utilities for replacing the raylib logger with the `log` create.

use std::{convert::TryInto, ffi::c_void};

use num_traits::FromPrimitive;
use printf::printf;

/// Direct mapping of raylib's log levels
/// See: https://github.com/raysan5/raylib/blob/d875891a3c2621ab40733ca3569eca9e054a6506/parser/raylib_api.json#L985-L1026
#[derive(FromPrimitive)]
enum RaylibLogLevel {
All = 0,
Trace = 1,
Debug = 2,
Info = 3,
Warning = 4,
Error = 5,
Fatal = 6,
None = 7,
}

/// Logging callback that is passed through to raylib over the ffi boundary.
#[cfg(target_os = "linux")]
#[no_mangle]
pub unsafe extern "C" fn log_callback(
level: i32,
message: *const i8,
args: *mut crate::ffi::__va_list_tag,
) {
// Get the message as a string. This is calling back to C code with a reasonably safe sprintf implementation.
let formatted_message = printf(message, args as *mut c_void);

// Handle the log level and fall back on info!
match RaylibLogLevel::from_u32(level.try_into().unwrap()) {
Some(level) => match level {
RaylibLogLevel::Trace => log::trace!(target:"raylib", "{}", formatted_message),
RaylibLogLevel::Debug => log::debug!(target:"raylib", "{}", formatted_message),
RaylibLogLevel::Warning => log::warn!(target:"raylib", "{}", formatted_message),
RaylibLogLevel::Error => log::error!(target:"raylib", "{}", formatted_message),
RaylibLogLevel::Fatal => log::error!(target:"raylib", "{}", formatted_message),
_ => log::info!(target:"raylib", "{}", formatted_message),
},
None => {
log::info!(target:"raylib", "{}", formatted_message)
}
}
}
16 changes: 14 additions & 2 deletions raylib/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub mod text;
pub mod texture;
pub mod vr;
pub mod window;
mod log_hooks;

use crate::ffi;
use std::ffi::CString;
Expand Down Expand Up @@ -82,6 +83,7 @@ pub struct RaylibBuilder {
width: i32,
height: i32,
title: String,
using_log_crate: bool
}

/// Creates a `RaylibBuilder` for choosing window options before initialization.
Expand Down Expand Up @@ -156,6 +158,12 @@ impl RaylibBuilder {
self
}

/// Switches the internal logger to use the `log` crate
pub fn replace_logger(&mut self) -> &mut Self {
self.using_log_crate = true;
self
}

/// Builds and initializes a Raylib window.
///
/// # Panics
Expand Down Expand Up @@ -186,7 +194,7 @@ impl RaylibBuilder {
unsafe {
ffi::SetConfigFlags(flags as u32);
}
let rl = init_window(self.width, self.height, &self.title);
let rl = init_window(self.width, self.height, &self.title, self.using_log_crate);
(rl, RaylibThread(PhantomData))
}
}
Expand All @@ -196,11 +204,15 @@ impl RaylibBuilder {
/// # Panics
///
/// Attempting to initialize Raylib more than once will result in a panic.
fn init_window(width: i32, height: i32, title: &str) -> RaylibHandle {
fn init_window(width: i32, height: i32, title: &str, use_log_crate: bool) -> RaylibHandle {
if IS_INITIALIZED.load(Ordering::Relaxed) {
panic!("Attempted to initialize raylib-rs more than once!");
} else {
unsafe {
#[cfg(target_os = "linux")]
if use_log_crate {
ffi::SetTraceLogCallback(Some(log_hooks::log_callback));
}
let c_title = CString::new(title).unwrap();
ffi::InitWindow(width, height, c_title.as_ptr());
}
Expand Down
5 changes: 4 additions & 1 deletion raylib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,11 @@ pub use crate::core::logging::*;
pub use crate::core::misc::{get_random_value, open_url};
pub use crate::core::*;

#[macro_use]
extern crate num_derive;

// Re-exports
#[cfg(feature = "with_serde")]
pub use serde;
#[cfg(feature = "nalgebra_interop")]
pub use nalgebra as na;
pub use nalgebra as na;