7个版本
0.2.5 | 2020年9月17日 |
---|---|
0.2.4 | 2020年9月17日 |
0.2.3 | 2020年6月29日 |
0.1.0 | 2020年5月13日 |
#3 in #activate
31 每月下载次数
在 2 crates 中使用
8KB
102 代码行数(不含注释)
## 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");
}
```
依赖项
~4.5MB
~68K SLoC