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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
use std::thread;
use std::sync::{Once, ONCE_INIT};
use std::sync::Arc;
use std::cmp;
use std::fmt;

use queue::MessagesQueue;

lazy_static! {
    pub static ref LOG: Log = Log::init();
}

pub static mut MAX_LEVEL: Level = Level::Info;
static mut LOGGER: &'static Logger = &DefaultLogger;
static START: Once = ONCE_INIT;

static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];

pub struct Log {
    pub queue: Arc<MessagesQueue<Record>>
}

impl Log {
    pub fn init() -> Log {
        let queue = MessagesQueue::with_capacity(1024);

        let queue2 = queue.clone();
        thread::spawn(move || {
            loop {
                let recored = queue2.pop();
                unsafe {LOGGER.log(&recored)};
            }
        });

        Log {
            queue: queue
        }
    }

    pub fn push(&self, record: Record) {
        self.queue.push(record);
    }
}

pub fn init(level: Level, logger: &'static Logger) {
    unsafe {
        START.call_once(move || {
            MAX_LEVEL = level;
            LOGGER = logger;
        });
    }
}

#[repr(usize)]
#[derive(Copy, Eq, Debug, Hash)]
pub enum Level {
    Error = 1,
    Warn,
    Info,
    Debug,
    Trace,
}

impl Clone for Level {
    #[inline]
    fn clone(&self) -> Level {
        *self
    }
}

impl PartialEq for Level {
    #[inline]
    fn eq(&self, other: &Level) -> bool {
        *self as usize == *other as usize
    }
}

impl PartialOrd for Level {
    #[inline]
    fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Level {
    #[inline]
    fn cmp(&self, other: &Level) -> cmp::Ordering {
        (*self as usize).cmp(&(*other as usize))
    }
}

impl fmt::Display for Level {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", LOG_LEVEL_NAMES[*self as usize])
    }
}

pub trait Logger {
    fn log(&self, record: &Record);
}

#[derive(Debug, Clone)]
pub struct Record {
    pub metadata: Metadata,
    pub message: String,
    pub module_path: Option<String>,
    pub file: Option<String>,
    pub line: Option<u32>
}

impl Record {
    pub fn new(metadata: Metadata, message: String, module_path: Option<String>, file: Option<String>, line: Option<u32>) -> Record {
        Record {
            metadata: metadata,
            message: message,
            module_path: module_path,
            file: file,
            line: line
        }
    }

    pub fn empty() -> Record {
        Record::new(Metadata::empty(), "".to_owned(), None, None, None)
    }

    pub fn metadata(&mut self, metadata: Metadata) -> &mut Record {
        self.metadata = metadata;
        self
    }

    pub fn message(&mut self, message: String) -> &mut Record {
        self.message = message;
        self
    }

    pub fn module_path(&mut self, module_path: Option<String>) -> &mut Record {
        self.module_path = module_path;
        self
    }

    pub fn file(&mut self, file: Option<String>) -> &mut Record {
        self.file = file;
        self
    }

    pub fn line(&mut self, line: Option<u32>) -> &mut Record {
        self.line = line;
        self
    }
}

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct Metadata {
    pub level: Level,
    pub target: String
}

impl Metadata {
    pub fn new(level: Level, target: String) -> Metadata {
        Metadata {
            level: level,
            target: target
        }
    }

    pub fn empty() -> Metadata {
        Metadata::new(Level::Info, "".to_owned())
    }

    pub fn level(&mut self, level: Level) -> &mut Metadata {
        self.level = level;
        self
    }

    pub fn target(&mut self, target: String) -> &mut Metadata {
        self.target = target;
        self
    }
}

pub struct DefaultLogger;

use color::{Print, Color};
use chrono::{Local, DateTime};

impl Logger for DefaultLogger {
    fn log(&self, record: &Record) {
        
        let color = match record.metadata.level {
            Level::Trace => {
                Color::Purple
            }
            Level::Debug => {
                Color::Blue
            }
            Level::Info => {
                Color::Green
            }
            Level::Warn => {
                Color::Yellow
            }
            Level::Error => {
                Color::Red
            }
        };

        let time_now: DateTime<Local> = Local::now();

        println!(
            "{} {} | {} | {}",
            Print::new(format!("[{}]", record.metadata.target)).foreground(color),
            Print::new(time_now.format("%Y/%m/%d - %H:%M:%S %z").to_string()).foreground(color),
            Print::new(&record.message).foreground(color),
            Print::new(format!("module:{:?} file:{:?} line:{:?}", &record.module_path, &record.file, &record.line)).foreground(color)
        );
    }
}