logging 0.1.0

logging inspired by the python logging fascility.
Documentation
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//!
//! A logging fascility inspired by the python logging framework.
//!
//! This library implements named herachical loggers which have message
//! handlers associated with them.
//!
//! The framework is  intended more for people who want to set log levels for there application
//! without the need to recompile the software.
//!
//! ## features
//!
//! + Thread safe.
//! + Easy to extend.
//! + Log handlers can be added and removed at runtime.
//! + Log levels can be changed at runtime.
//!
//! ## behavior
//!
//! + Via default there is no log handler added.
//! + The default log level of all loggers is `DEFAULT`.
//! + Log messages bubble up to their parents and will be logged by all intermediate handlers.
//!
//! ## usage
//!
//! ```rust
//! extern crate logging;
//!
//! use std::sync::Arc;
//!
//! struct MyOwnHandler {}
//!
//! impl logging::Handler for MyOwnHandler {
//!   fn emit(&self, msg: &logging::Message) {
//!     print!("{:7} | {}", msg.name, msg.msg);
//!   }
//! }
//!
//! fn main() {
//!   // you will see nothing, because no handler added yet
//!   logging::debug("app started");
//!
//!   logging::root().add_handler(Arc::new(Box::new(MyOwnHandler {})));
//!
//!   let log = logging::get("myapp");
//!   log.add_handler(logging::ConsoleHandler::new());
//!
//!   // will be printed by both handlers
//!   log.info("created".to_owned());
//!   {
//!     let sub_log = logging::get("myapp.special");
//!     sub_log.debug("some other stuff");
//!   }
//!
//!   log.level = logging::Level::WARN;
//!   // will not be printed by the handler of `myapp`.
//!   log.info("unly plain not in color");
//! }
//! ```
//!
extern crate ansi_term;

use ansi_term::Colour;
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, Write};
use std::sync::{Arc, RwLock};
use std::time::{SystemTime, UNIX_EPOCH};

///
/// The aviable logging levels.
///
#[derive(PartialEq, PartialOrd, Clone, Copy)]
pub enum Level {
    /// For debuging and tracing information.
    DEBUG,
    /// For general informations.
    INFO,
    /// Warning about non critical male behaviour.
    WARN,
    /// This is when something went very wrong.
    ERROR,
    /// The sh*t hits the fan, you possible should run for your live.
    FATAL,
    /// Nothing will be logged.
    NONE,
}

///
/// A message to be logged.
///
pub struct Message {
    /// The level of the message.
    level: Level,
    /// The full name of the logger.
    name: String,
    /// The timestamp of creation.
    created: SystemTime,
    /// The message string itself.
    msg: String,
}


///
/// Handels an emitted message.
///
pub trait Handler: Send + Sync {
    /// Actually do something with the message.
    fn emit(&self, message: &Message);
}


///
/// Colorfull console logging
///
/// + uses: https://github.com/ogham/rust-ansi-term
///
pub struct ConsoleHandler {}

impl ConsoleHandler {
    pub fn new() -> Arc<Box<Handler>> {
        Arc::new(Box::new(ConsoleHandler {}))
    }
}


impl Handler for ConsoleHandler {
    fn emit(&self, message: &Message) {
        let data = match message.level {
            Level::DEBUG => Colour::Cyan.paint(format!("{} | {}\n", message.name, message.msg)),
            Level::INFO => Colour::Green.paint(format!("{} | {}\n", message.name, message.msg)),
            Level::WARN => Colour::Yellow.paint(format!("{} | {}\n", message.name, message.msg)),
            Level::ERROR => Colour::Red.paint(format!("{} | {}\n", message.name, message.msg)),
            Level::FATAL => Colour::Red.paint(format!("{} | {}\n", message.name, message.msg)),
            Level::NONE => Colour::White.paint(""),
        };

        let stdout = io::stdout();
        let mut handle = stdout.lock();

        handle.write(data.to_string().as_bytes()).unwrap();
        handle.flush().unwrap();
    }
}


///
/// Logging to a file
///
/// ```
/// extern crate logging;
///
/// fn main() {
///   let handler = logging::FileHandler::new("my.log");
///   logging::root().add_handler(handler);
/// }
///
pub struct FileHandler {
    out: Arc<RwLock<File>>,
}


impl FileHandler {
    pub fn new(filename: &str) -> Arc<Box<Handler>> {
        Arc::new(Box::new(FileHandler {
            out: Arc::new(RwLock::new(File::create(filename).unwrap())),
        }))
    }
}


impl Handler for FileHandler {
    fn emit(&self, message: &Message) {
        let dur = message.created.duration_since(UNIX_EPOCH).unwrap();

        let data = match message.level {
            Level::DEBUG => {
                format!(
                    "{:9}.{:0.09} | DEBUG | {:15} | {}\n",
                    dur.as_secs(),
                    dur.subsec_nanos(),
                    message.name,
                    message.msg
                )
            }
            Level::INFO => {
                format!(
                    "{:9}.{:0.09} |  INFO | {:15} | {}\n",
                    dur.as_secs(),
                    dur.subsec_nanos(),
                    message.name,
                    message.msg
                )
            }
            Level::WARN => {
                format!(
                    "{:9}.{:0.09} |  WARN | {:15} | {}\n",
                    dur.as_secs(),
                    dur.subsec_nanos(),
                    message.name,
                    message.msg
                )
            }
            Level::ERROR => {
                format!(
                    "{:9}.{:0.09} | ERROR | {:15} | {}\n",
                    dur.as_secs(),
                    dur.subsec_nanos(),
                    message.name,
                    message.msg
                )
            }
            Level::FATAL => {
                format!(
                    "{:9}.{:0.09} | FATAL | {:15} | {}\n",
                    dur.as_secs(),
                    dur.subsec_nanos(),
                    message.name,
                    message.msg
                )
            }
            Level::NONE => "".to_string(),
        };

        let mut out = self.out.write().unwrap();
        out.write(data.as_bytes()).unwrap();
        out.flush().unwrap();
    }
}

///
/// A logger node.
///
/// **note:** Normaly you should never have to create an instance by yourself.
///
#[derive(Clone)]
pub struct _Logger {
    _name: String,
    _full_name: String,
    /// The level of the logger.
    pub level: Level,
    _parent: Option<Arc<_Logger>>,
    _handlers: Arc<RwLock<Vec<Arc<Box<Handler>>>>>,
    _children: Arc<RwLock<HashMap<String, Arc<_Logger>>>>,
}


impl _Logger {
    ///
    ///  Add a new handler to the logger node.
    ///
    pub fn add_handler(&self, handler: Arc<Box<Handler>>) {
        let mut hs = self._handlers.write().unwrap();
        hs.push(handler);
    }

    //
    // Removes all handlers from this logging node.
    //
    pub fn clear_handlers(&self) {
        let mut hs = self._handlers.write().unwrap();
        hs.clear();
    }

    /// Returns the name part of this logger.
    pub fn name(&self) -> String {
        self._name.clone()
    }

    /// Returns the full name of the logger.
    pub fn full_name(&self) -> String {
        self._full_name.clone()
    }

    ///
    /// Logs a message.
    ///
    pub fn log(&self, level: Level, msg: &str) {
        if self.level <= level {
            let message = Message {
                level: level,
                name: self._full_name.clone(),
                created: SystemTime::now(),
                msg: String::from(msg),
            };

            self.log_msg(&message);
        }
    }

    fn log_msg(&self, message: &Message) {
        let hs = self._handlers.read().unwrap();
        for h in hs.iter() {
            h.emit(&message);
        }

        if let Some(ref parent) = self._parent {
            parent.log_msg(message);
        }
    }

    ///
    /// Logs a debug message.
    ///
    pub fn debug(&self, fmt: &str) {
        self.log(Level::DEBUG, fmt);
    }

    ///
    /// Logs a info message.
    ///
    pub fn info(&self, fmt: &str) {
        self.log(Level::INFO, fmt);
    }

    ///
    /// Logs a warn message.
    ///
    pub fn warn(&self, fmt: &str) {
        self.log(Level::WARN, fmt);
    }

    ///
    /// Logs a error message.
    ///
    pub fn error(&self, fmt: &str) {
        self.log(Level::ERROR, fmt);
    }

    ///
    /// Logs a fatal message.
    ///
    pub fn fatal(&self, fmt: &str) {
        self.log(Level::FATAL, fmt);
    }
}

/// A logger instance.
pub type Logger = Arc<_Logger>;

static mut ROOT: *const Logger = 0 as *const Logger;

fn init() {
    // make rust unsafe again!
    unsafe {
        if ROOT == (0 as *const Logger) {
            let root = Box::new(Arc::new(_Logger {
                _name: String::new(),
                _full_name: String::new(),
                level: Level::DEBUG,
                _parent: None,
                _handlers: Arc::new(RwLock::new(Vec::new())),
                _children: Arc::new(RwLock::new(HashMap::new())),
            }));

            // root.add_handler(ConsoleHandler::new());
            ROOT = std::mem::transmute(root);
        }
    }
}

///
/// Gets the root logger.
///
pub fn root() -> Logger {
    init();
    unsafe { (*ROOT).clone() }
}

///
/// Convenient debug log to the root logger.
///
pub fn debug(fmt: &str) {
    init();

    let result = unsafe { (*ROOT).clone() };

    result.log(Level::DEBUG, fmt);
}

///
/// Convenient info log to the root logger.
///
pub fn info(fmt: &str) {
    init();

    let result = unsafe { (*ROOT).clone() };

    result.log(Level::INFO, fmt);
}

///
/// Convenient warn log to the root logger.
///
pub fn warn(fmt: &str) {
    init();

    let result = unsafe { (*ROOT).clone() };

    result.log(Level::WARN, fmt);
}

///
/// Convenient error log to the root logger.
///
pub fn error(fmt: &str) {
    init();

    let result = unsafe { (*ROOT).clone() };

    result.log(Level::ERROR, fmt);
}

///
/// Convenient fatal log to the root logger.
///
pub fn fatal(fmt: &str) {
    init();

    let result = unsafe { (*ROOT).clone() };

    result.log(Level::FATAL, fmt);
}

///
/// Gets a Logger instance by it's name.
///
/// ```
/// let log = logging::get("my.app".to_owned());
/// ```
///
pub fn get(name: &str) -> Logger {
    init();

    let path: Vec<&str> = name.split(".").collect();
    let mut result = unsafe { (*ROOT).clone() };

    for (idx, step) in path.iter().enumerate() {
        result = {
            let mut map = result._children.write().unwrap();

            map.entry(step.to_string())
                .or_insert_with(|| {
                    let full = path[1..idx + 1].iter().fold(
                        String::from(path[0]),
                        |a, b| format!("{}.{}", a, b),
                    );

                    Arc::new(_Logger {
                        _name: step.to_string(),
                        _full_name: full,
                        level: Level::DEBUG,
                        _parent: Some(result.clone()),
                        _handlers: Arc::new(RwLock::new(Vec::new())),
                        _children: Arc::new(RwLock::new(HashMap::new())),
                    })
                })
                .clone()
        };
    }

    result
}