1use std::sync::Mutex;
2
3use lazy_static::lazy_static;
4use log::Level;
5
6lazy_static! {
7 static ref GLOBAL_CONTEXT: Mutex<Option<GlobalContextValue>> = Mutex::new(None);
8}
9
10pub struct GlobalContext {
11}
12
13impl GlobalContext {
14 pub fn new(name: &str) -> GlobalContext {
15 GlobalContext::new_conditional(Level::iter().next().unwrap(), name)
16 }
17
18 pub fn new_conditional(min_level: Level, name: &str) -> GlobalContext {
19 let message = format!("[{}] ", name);
20
21 {
22 let mut context = GLOBAL_CONTEXT.lock().unwrap();
23 if context.is_some() {
24 panic!("An attempt to set a nested global context");
25 }
26 context.replace(GlobalContextValue {
27 min_level,
28 message
29 });
30 }
31
32 GlobalContext{}
33 }
34
35 pub(crate) fn get(level: Level) -> String {
36 match GLOBAL_CONTEXT.lock().unwrap().as_ref() {
37 Some(context) if level >= context.min_level => context.message.clone(),
38 _ => String::new(),
39 }
40 }
41}
42
43impl Drop for GlobalContext {
44 fn drop(&mut self) {
45 *GLOBAL_CONTEXT.lock().unwrap() = None;
46 }
47}
48
49struct GlobalContextValue {
50 min_level: Level,
51 message: String,
52}