use crate::log::{SerializationMethod, Subscriber};
use std::io::Write;
use std::sync::Mutex;
use std::thread::JoinHandle;
use tracing_core::dispatcher::with_default;
use tracing_core::{Dispatch, Level};
lazy_static::lazy_static! {
static ref GLOBAL_LOGGER: Mutex<Option<Subscriber>> = Mutex::new(None);
}
pub struct GlobalLoggerGuard;
impl Drop for GlobalLoggerGuard {
fn drop(&mut self) {
if let Ok(mut guard) = GLOBAL_LOGGER.lock() {
(*guard).take(); }
}
}
pub fn set_global_logger(
dest: impl Write + Send + 'static,
level: Level,
method: SerializationMethod,
) -> GlobalLoggerGuard {
*GLOBAL_LOGGER.lock().expect("Cannot lock to set global logger") = Some(Subscriber::new(dest, level, method));
GlobalLoggerGuard
}
pub fn remove_global_logger() {
*GLOBAL_LOGGER.lock().expect("Cannot lock to clear global logger") = None;
}
pub fn run_with_global_logger<T>(f: impl FnOnce() -> T) -> T {
let global = GLOBAL_LOGGER
.lock()
.expect("Cannot lock to get global logger")
.clone()
.map_or_else(Dispatch::none, Dispatch::new);
with_default(&global, f)
}
pub fn thread_spawn_with_global_logger<T>(f: impl FnOnce() -> T + Send + 'static) -> JoinHandle<T>
where
T: Send + 'static,
{
std::thread::spawn(move || run_with_global_logger(f))
}