use crate::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use once_cell::sync::Lazy;
#[derive(Clone)]
pub struct Global(Arc<Logger>);
static GLOBAL: Lazy<Mutex<HashMap<Arc<str>, Global>>> = Lazy::new(|| Mutex::new(HashMap::new()));
impl Global {
pub fn new(name: impl Into<String>) -> Self {
let name: String = name.into();
let mut map = GLOBAL.lock().unwrap();
if let Some(logger) = map.get(name.as_str()) {
return logger.clone();
}
let logger = Self(Arc::new(Logger::default(&name)));
map.insert(name.into(), logger.clone());
logger
}
pub fn register<F: Formatter>(name: impl Into<String>, config: Config) -> Self {
let name: String = name.into();
let logger = Self(Arc::new(Logger::new::<F>(&name, config)));
GLOBAL.lock().unwrap().insert(name.into(), logger.clone());
logger
}
pub fn unregister(name: impl AsRef<str>) {
GLOBAL.lock().unwrap().remove(name.as_ref());
}
#[track_caller]
pub fn session(name: impl Into<String>, session: impl Into<String>, silent: bool) -> Session {
Self::new(name).session(session, silent)
}
#[track_caller]
pub fn session_then<F, T>(&self, name: impl Into<String>, silent: bool, callable: F) -> T
where F: FnOnce(Session) -> T
{
callable(self.session(name, silent))
}
}
impl std::ops::Deref for Global {
type Target = Logger;
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}