#logger #logging #log #level #record #handler

mylogger

my simple logger for easy integration

7 releases

0.2.5 Sep 17, 2020
0.2.4 Sep 17, 2020
0.2.3 Jun 29, 2020
0.1.0 May 13, 2020

#97 in #record

31 downloads per month
Used in 2 crates

MIT license

8KB
102 lines

## MyLogger uses std runtime.
```
use chrono::prelude::*;
use chrono::Local;
use log::{info, Level, LevelFilter, Log, Metadata, Record};
use mylogger::MyLogger;
let mut mylogger = MyLogger::with_default_handler("asdf");
log::set_boxed_logger(Box::new(mylogger)).map(|()| log::set_max_level(LevelFilter::Info));

info!("this is the info message");
info!("this is the info message 11");
info!("this is the info message 222");
```
## custom handler
```
use mylogger::{MyLogger, HandlerTrait};
use chrono::prelude::*;
use chrono::Local;
use log::{info, Level, LevelFilter, Log, Metadata, Record};
pub struct CustomHandler {
    pub level: Level,
    pub name: String
}

impl CustomHandler {
    fn new(level: Level, name:String) -> CustomHandler {
        CustomHandler { level: level, name:name }
    }
}

impl HandlerTrait for CustomHandler {
    fn activate(&self, meta: &Metadata) -> bool {
        self.level >= meta.level()
    }
    fn format_record(&self, logger: &MyLogger, record: &Record) -> String {
        let now: DateTime<Local> = Local::now();
        let mut module_path = "".to_string();
        if let Some(path) = record.module_path() {
            module_path = path.to_string();
        }
        format!(
            "{}|{}|{}|{}|{} -> {}",
            &self.name,
            now.format("%Y-%m-%d %H:%M:%S"),
            module_path,
            record.target(),
            record.level(),
            record.args()
        )
    }
    fn log(&self, record: &Record, logger: &MyLogger) {
        if self.activate(record.metadata()) {
            let msg = self.format_record(logger, record);
            println!("{}", msg);
        }
    }
}

#[test]
fn custom_handler() {
    let mut mylogger = MyLogger::new("mylogger");
    log::set_boxed_logger(Box::new(mylogger)).map(|()| log::set_max_level(LevelFilter::Info));

    info!("this is the info message");
    info!("this is the info message 11");
    info!("this is the info message 222");
}
#[test]
fn custom_async_handler() {
    let mut mylogger = MyLogger::new("mylogger");
    let async_handler = AsyncDefaultHandler::new(level::Info, "async".to_string());
    mylogger.register_handler(Box::new(async_handler));
    log::set_boxed_logger(Box::new(mylogger)).map(|()| log::set_max_level(LevelFilter::Info));

    info!("this is the async info message");
    info!("this is the async info message 11");
    info!("this is the async info message 222");
}
```

Dependencies

~5MB
~70K SLoC