
100+ 重磅嘉宾出席 GOTC 2024! 499 专业观众票 【限时免费】
tklog是rust高性能结构化日志库,支持同步日志,异步日志,支持自定义日志的输出格式,支持按时间,按文件大小分割日志文件,支持日志文件压缩备份,支持官方日志库标准API,支持mod独立参数设置
- 官网
- 项目源码
- 仓库
- 《tklog与log4rs 的基准测试》
核心特点
- 高性能同步与异步日志记录:tklog 支持高效的同步与异步日志记录,确保即使在高负载环境下也能保持良好的性能。
- 灵活的日志格式定制:用户可以根据需要自定义日志输出格式,包括日志级别、时间戳格式等。
- 智能日志文件管理:支持按时间或文件大小自动分割日志文件,以及文件数量的滚动管理,有助于维持日志目录的整洁。
- 日志压缩与备份:支持对日志文件进行压缩归档,方便长期存储和备份。
- 官方标准 API 兼容:与 Rust 官方日志库标准 API 兼容,便于集成使用。
- 模块级配置:允许在不同的模块中独立设置日志参数,增强了灵活性。
0.0.9 版本更新
- v0.0.9 版本,tklog 引入了自定义日志处理函数的功能,开发者可以通过
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)异步
- 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日志,不再打印出来。
tklog 快速使用
- 添加依赖
[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


