Skip to main content

libobs_wrapper\logger/
mod.rs

1//! This module is used to provide a logger trait, which can be used to implement custom logging
2//! for the libobs console output.
3
4mod console;
5mod file;
6pub use console::ConsoleLogger;
7pub use file::FileLogger;
8
9use std::{fmt::Debug, os::raw::c_void, sync::Mutex};
10
11use lazy_static::lazy_static;
12use num_traits::FromPrimitive;
13
14use crate::{enums::ObsLogLevel, utils::c_format::format_va_list};
15
16lazy_static! {
17    /// We are using this as global variable because there can only be one obs context
18    pub(crate) static ref LOGGER: Mutex<Box<dyn ObsLogger>> = Mutex::new(Box::new(ConsoleLogger::new()));
19}
20
21/// # Safety
22/// This function is unsafe because it is called from C code.
23pub(crate) unsafe extern "C" fn extern_log_callback<V>(
24    log_level: i32,
25    msg: *const i8,
26    args: *mut V,
27    _params: *mut c_void,
28) {
29    let Some(level) = ObsLogLevel::from_i32(log_level) else {
30        eprintln!("Couldn't find log level {}", log_level);
31        return;
32    };
33
34    let Some(formatted) = format_va_list(msg, args) else {
35        eprintln!("Failed to format log message");
36        return;
37    };
38
39    let mut logger = LOGGER
40        .lock()
41        .unwrap_or_else(|poisoned| poisoned.into_inner());
42    logger.log(level, formatted);
43}
44
45pub trait ObsLogger
46where
47    Self: Send + Debug,
48{
49    fn log(&mut self, level: ObsLogLevel, msg: String);
50}
51
52pub(crate) fn internal_log_global(level: ObsLogLevel, msg: String) {
53    let mut logger = LOGGER
54        .lock()
55        .unwrap_or_else(|poisoned| poisoned.into_inner());
56    logger.log(level, msg);
57}