十、Rust 集成日志工具

十、Rust 集成日志工具
  
  Rust 日志工具大体有 log、env_logger 和 log、log4rs 两套方案,所以看起来 log 只是日志 特性,相当于 Java 中的接口,另外两个是实现。 对比后发现,log4rs 的使用方式更灵活,如可基于代码来配置,或基于 yaml、toml 文件来声明等。
  
  无论使用哪种实现,我们在工作中,都是面向的 log 特性来编码。

1、添加依赖

   Cargo.toml

[package]
name = "..."
edition = "2018"
...
[dependencies]
log4rs = "1.0.0-alpha-2"    # log4rs for log
...

2、配置 log4rs

   根据项目首页的介绍,使用 log4rs 需要提供 log4rs.yaml 配置文件,并通过一行代码来初始化 log 引擎。

   log4rs.yaml

refresh_rate: 30 seconds
appenders:
  stdout:
    kind: console
    encoder:
      pattern: "{d(%Y-%m-%d %H:%M:%S)} {h({l})} [{M}] - {m}{n}"
root:
  level: debug
  appenders:
    - stdout

   为使项目界面保持简单,我们将这行初始化,放在了一个项目全局启动的地方。
  boot/mod.rs

pub fn start() {
    log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
    boot::db::init_db_pool()
    // TODO ...
}

   Log4rs 的 pattern 支持以下内容:

  • d,data 日期,默认为 ISO 9601 格式,可以通过 {d(%Y-%m-%d %H:%M:%S)} 这种方式改变日期格式
  • l,log 级别
  • h,高亮显示,debug 灰,info 绿,warn 黄,error 红
  • f,消息所在文件
  • L,消息所在行数
  • M,Module log 消息所在模块
  • m,message log 消息
  • n,具体平台的换行符
  • X,mdc 映射诊断环境
  • P,pid - The current process id.
  • t,target - The target of the log message. 可能与 Module 相同
  • T,thread - The name of the current thread. 线程名称
  • I,thread_id - The ID of the current thread. 线程 ID

https://docs.rs/log4rs/latest/log4rs/encode/pattern/index.html#formatters

3、使用日志

   将前面的章节的 数据源 初始化部分,改为用 日志 输出。

pub fn init_db_pool() {
    if let Some(db) = &crate::boot::global().postgres {
        let pool = PgPoolOptions::new()
            .min_connections(db.min)
            .max_connections(db.max)
            .connect_lazy(&db.dsn).unwrap();
        assert!(POSTGRES_POOL.set(pool).is_ok());
        log::info!("DataSource {}   {} ~ {}", db.dsn, db.min, db.max)
    }
}

4、查看日志

   以 Mac + Clion 为例,Control + D,以 debug 模式启动服务。

2020-11-18 17:09:09 INFO [favorites::boot::db] - DataSource postgres://username:password@ip:5432/postgres   5 ~ 15
2020-11-18 17:09:09 INFO [actix_server::builder] - Starting 8 workers
2020-11-18 17:09:09 INFO [actix_server::builder] - Starting "actix-web-service-0.0.0.0:8080" service on 0.0.0.0:8080

 
  完事儿 ~
  
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值