tklog是rust高性能结构化日志库,支持同步日志,异步日志,支持自定义日志的输出格式,支持按时间,按文件大小分割日志文件,支持日志文件压缩备份,支持官方日志库标准API,支持mod独立参数设置
set_custom_handler()
方法来定义自己的日志处理逻辑。 说明:custom_handler
来自 bronya0 给 go-logger 添加的等价功能 CustomHandler
, 该功能在go编程中非常实用,在rust中同样很实用,它可以由开发者通过捕获日志记录时的日志级别,日志模块,文件名等信息,做必要的业务处理,如捕获error日志进行邮件通知等。因此在同为日志框架的tklog
添加相同的功能,可以分别在同步日志与异步日志中添加
LOG.set_custom_handler(custom_handler)
同步ASYNC_LOG.set_custom_handler(custom_handler)
异步#[test]
fn test_custom() {
fn custom_handler(lc: &LogContext) -> bool {
println!("level >>>>>>>>>>>>>>>>>{:?}", lc.level);
println!("message >>>>>>>>>>>>>>>>>{:?}", lc.log_body);
println!("filename >>>>>>>>>>>>>>>>>{:?}", lc.filename);
println!("line >>>>>>>>>>>>>>>>>{:?}", lc.line);
println!("modname >>>>>>>>>>>>>>>>>{:?}", lc.modname);
if lc.level == LEVEL::Debug {
println!("{}", "debug now");
return false;
}
true
}
LOG.set_custom_handler(custom_handler);
debug!("000000000000000000");
info!("1111111111111111111");
thread::sleep(Duration::from_secs(1))
}
执行结果
---- test_custom stdout ----
level >>>>>>>>>>>>>>>>>Debug
message >>>>>>>>>>>>>>>>>"000000000000000000"
filename >>>>>>>>>>>>>>>>>"tests estsynclog.rs"
line >>>>>>>>>>>>>>>>>143
modname >>>>>>>>>>>>>>>>>"testsynclog"
debug now
level >>>>>>>>>>>>>>>>>Info
message >>>>>>>>>>>>>>>>>"1111111111111111111"
filename >>>>>>>>>>>>>>>>>"tests estsynclog.rs"
line >>>>>>>>>>>>>>>>>144
modname >>>>>>>>>>>>>>>>>"testsynclog"
[INFO] 2024-08-05 15:39:07 testsynclog.rs 144:1111111111111111111
fn custom_handler(lc: &LogContext) -> bool
返回true时,tklog调用custom_handler
执行自定义函数后,继续执行tklog的打印流程。当返回false时,tklog不再执行tklog的打印程序。直接返回。如示例中所示,当年日志级别为Debug时,返回false,所以,tklog的Debug日志,不再打印出来。[dependencies]
tklog = "0.0.9" # "0.0.x" 当前版本
use tklog::{trace,debug, error, fatal, info,warn}
fn testlog() {
trace!("trace>>>>", "aaaaaaaaa", 1, 2, 3, 4);
debug!("debug>>>>", "bbbbbbbbb", 1, 2, 3, 5);
info!("info>>>>", "ccccccccc", 1, 2, 3, 5);
warn!("warn>>>>", "dddddddddd", 1, 2, 3, 6);
error!("error>>>>", "eeeeeeee", 1, 2, 3, 7);
fatal!("fatal>>>>", "ffffffff", 1, 2, 3, 8);
}
[TRACE] 2024-05-26 11:47:22 testlog.rs 27:trace>>>>,aaaaaaaaa,1,2,3,4
[DEBUG] 2024-05-26 11:47:22 testlog.rs 28:debug>>>>,bbbbbbbbb,1,2,3,5
[INFO] 2024-05-26 11:47:22 testlog.rs 29:info>>>>,ccccccccc,1,2,3,5
[WARN] 2024-05-26 11:47:22 testlog.rs 30:warn>>>>,dddddddddd,1,2,3,6
[ERROR] 2024-05-26 11:47:22 testlog.rs 31:error>>>>,eeeeeeee,1,2,3,7
[FATAL] 2024-05-26 11:47:22 testlog.rs 32:fatal>>>>,ffffffff,1,2,3,8