1. 引子
最近想要迁移一部分java应用至rust,在实际体验了tklog,log4rs,和tracing三款流行的日志框架后,最后选用了tracing,log4rs的文件备份文件名没有时间,不便于管理,tklog的功能稍显简陋,在使用uselog()后会将某些底层包日志输出至终端,即使过滤掉某第三方个包(假设叫A)之后,这个包依赖的第三方包(A依赖的第三方包B)的日志依旧会被显示,但是tklog本身又无法显示包名,只能显示文件名,根本不知道这个日志是从哪个包漏出来的XD,最后在经历多次尝试后最终选定了使用最广泛的tracing!
2. 加入tracing包
| |
| log = "0.4" |
| |
| tracing = "0.1" |
| |
| tracing-appender = { package = "tracing-appender-plus", version = "0.2", features = ["local-time",] } |
| |
| tracing-subscriber = { version = "0.3", features = ["time", "env-filter"] } |
| |
| time = { version = "0.3", features = ["macros"] } |
3. 上代码
| use time::macros::{format_description, offset}; |
| use tracing_appender::{non_blocking::WorkerGuard, rolling::{RollingFileAppender, Rotation}}; |
| use tracing_subscriber::{fmt::{time::OffsetTime, writer::MakeWriterExt}, EnvFilter}; |
| pub fn tracing_init() -> (WorkerGuard, WorkerGuard) { |
| |
| let time_fmt = |
| format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]"); |
| let timer = OffsetTime::new(offset!(+8), time_fmt); |
| |
| let file_appender = RollingFileAppender::builder() |
| .rotation(Rotation::DAILY) |
| .filename_prefix("service") |
| .filename_suffix("log") |
| .max_log_files(30) |
| .build("logs") |
| .expect("failed to initialize rolling file appender"); |
| |
| let (stdout, guard1) = tracing_appender::non_blocking(std::io::stdout()); |
| let (file, guard2) = tracing_appender::non_blocking(file_appender); |
| |
| tracing_subscriber::fmt() |
| .with_env_filter(EnvFilter::from( |
| "warn,actix_web1=debug,nacos_rust_client=info", |
| )) |
| .with_line_number(true) |
| .with_thread_ids(true) |
| .with_ansi(false) |
| .with_timer(timer) |
| .with_writer(file.and(stdout)) |
| .init(); |
| (guard1, guard2) |
| |
| } |
4. 参考文献
- https://probiecoder.cn/rust/tracing.html
- https://blog.csdn.net/qq_54714089/article/details/136717431
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 易语言 —— 开山篇