1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use crate::writer::Writer;
use crate::event::Event;
use crate::config::Config;
use crate::appender::{FileAppender, ConsoleAppender};

use std::thread;
use std::sync::{mpsc, Mutex};

pub enum EventType {
    Log(Event),
    Terminate,
}

lazy_static! {
    pub static ref LOGGER_OBJ : Logger = Logger::init();
}

#[allow(unused)]
pub struct Logger {
    wr_th: Mutex<Option<thread::JoinHandle<()>>>,
    fmt_th: Mutex<Option<thread::JoinHandle<()>>>,
    poster: Mutex<mpsc::Sender<EventType>>,
}

impl Logger {
    pub fn init() -> Self {
        let mut w = Writer::new();
        let poster = w.get_poster();

        let console_conf = Config::instance().console_conf();
        if console_conf.switch {
            w.add_appender(Box::new(ConsoleAppender::new(console_conf)));
        }

        let file_conf = Config::instance().file_conf();
        if file_conf.switch {
            w.add_appender(Box::new(FileAppender::new(file_conf, Config::instance().file_temp_buf(), Config::instance().file_log_dir())));
        }

        // init writer thread
        let wr_th = thread::spawn(move ||{
            let mut w = w;
            loop {
                w.fetch_logs();

                if w.is_terminate() {
                    //println!("writer thread exit!!");
                    break;
                }
                // release cpu every frame 
                // todo : to be more intelligent
                //thread::sleep(Duration::from_micros(1u64));
                thread::yield_now();
            }
        });

        let (tx, rx) = mpsc::channel();
        let fmt_th = thread::spawn(move || {
            let mut is_stop: bool = false;
            loop {
                for msg in rx.iter() {
                    // todo : handle msg 
                    match msg {
                        EventType::Log(log) => {
                            poster.insert_log(log.to_logic());
                        },
                        EventType::Terminate => {
                            is_stop = true;
                            break;
                        },
                    }
                }

                if is_stop {
                    //println!("farmat thread exit!!");
                    poster.set_terminate(true);
                    break;
                }

                // release cpu every frame 
                // todo : to be more intelligent
                //thread::sleep(Duration::from_micros(1u64));
                thread::yield_now();
            }
        });

        Self {
            wr_th: Mutex::new(Some(wr_th)),
            fmt_th: Mutex::new(Some(fmt_th)),
            poster: Mutex::new(tx),
        }
    }    

    pub fn get_poster(&self) -> mpsc::Sender<EventType> {
        self.poster.lock().unwrap().clone()
    }

    pub fn close() {
        //println!("logger closing");
        if let Err(e) = LOGGER_OBJ.get_poster().send(EventType::Terminate) {
            panic!("can not send terminate info to log threads! error: {}", e.to_string());
        }
        if let Some(w_th) = LOGGER_OBJ.wr_th.lock().expect("get write thread failed").take() {
            w_th.join().expect("Couldn't join on the associated thread");
        }
        if let Some(fmt_th) = LOGGER_OBJ.fmt_th.lock().expect("get format thread failed").take() {
            fmt_th.join().expect("Couldn't join on the associated thread");
        }
    }
    
}

pub trait SendEvent {
    fn send_event(&self, e: Event);
}

#[allow(unused)]
impl SendEvent for mpsc::Sender<EventType> {
    fn send_event(&self, e: Event) {
        self.send(EventType::Log(e));
    }
}

pub struct ThreadLocalLogger {
    sender: mpsc::Sender<EventType>,
    thread_tag: String,
} 

impl ThreadLocalLogger {
    pub fn new() -> Self {
        let tid: u64 = unsafe { std::mem::transmute(thread::current().id()) };
        let thread_tag = match thread::current().name() {
            Some(ref name) => format!("{}:[{}]", name.to_string(), tid),
            None => format!("thread:[{}]", tid),
        };

        Self {
            sender: LOGGER_OBJ.get_poster(),
            thread_tag, 
        }
    }

    pub fn get_thread_tag(&self) -> String {
        self.thread_tag.clone()
    }

    pub fn get_sender(&self) -> &mpsc::Sender<EventType> {
        &self.sender
    }

}

impl Default for ThreadLocalLogger {
    fn default() -> Self {
        Self::new()
    }
}