Rust - log 日誌輸入到文件

一、添加 log 依賴庫

log4rs 是模仿log4j的java庫

[dependencies]
log = "0.4.8"
log4rs = "0.11.0"
二、配置詳解

1、appenders 輸出到什麼地方

a) kind:指定類型

  • console:控制檯
  • file:普通的日誌文件
  • rolling_file:可以分割處理的日誌文件

b) path:指定文件路徑

c) append: bool類型,是否拼接到文件尾部

d) encoder:指定日誌的輸出格式,默認爲kind: pattern

  • json:json格式輸出
  • pattern:模式輸出,如{d} [{t}] {l} {M}:{m}{n}
  • writer

e) policy:日誌分割處理的策略

  • compound:複合策略,多個策略規則
  • trigger:觸發策略 kind: sizelimit: 1024,按照文件大小,限制1024字節
  • roller:分割策略delete,超過1024字節,處理方式是刪除,也可以使用fixed_window壓縮存儲
三、配置示例
refresh_rate: 30 seconds

appenders:
  stdout:
    kind: console
  requests:
    kind: rolling_file
    path: "log/requests.log"
    encoder:
      kind: json
    policy:
      kind: compound
      trigger:
        kind: size
        limit: 10 mb
      roller:
        kind: fixed_window
        pattern: '{0}/requests.log.{{}}'
        base: 1
        count: 5

root:
  level: info
  appenders:
    - stdout
    - requests

#[macro_use]
extern crate log;
extern crate log4rs;

use std::thread;

fn main() {
    log4rs::init_file("log.yaml",Default::default()).unwrap();
    info!("Hello, world!");

    thread::sleep(std::time::Duration::from_secs(10));
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章