rust

rust下log工具

1.依赖

log = { version = "0.4.20", optional = true }
log4rs = { version = "1.3.0", optional = true }

2.接口示例

//! @Author: DengLibin
//! @Date: Create in 2023-11-02 14:25:29
//! @Description: 日志




use std::fmt::Display;

use log::{trace, info, debug, warn, error};

pub struct LogError {
    pub msg: String,
}
impl std::fmt::Display for LogError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.msg)
    }
}

// 自定义结果
pub type LogResult<T> = std::result::Result<T, LogError>;

//转换结果
fn check_result<T, E: Display>(result: Result<T, E>) -> LogResult<T> {
    return match result {
        Ok(r) => Result::Ok(r),
        Err(err) => Result::Err(LogError {
            msg: err.to_string(),
        }),
    };
}

/// @Author: DengLibin
/// @Date: Create in 2023-11-02 14:36:28
/// @Description: 初始化日志系统
pub fn init_log(log4rspath: &str) -> LogResult<()> {

    let r = log4rs::init_file(log4rspath, Default::default());
    check_result(r)
}


/// @Author: DengLibin
/// @Date: Create in 2023-11-02 14:37:15
/// @Description: 示例
pub fn demo(){
    trace!("this is trace:{}", 1);
    debug!("this is debug:{}", 1);
    info!("this is info:{}", 1);
    warn!("this is warn:{}", 2);
    error!("this is error:{}", 3);
}

3.log4rs配置文件

# 检查配置文件变动的时间间隔
refresh_rate: 30 seconds
# appender 负责将日志收集到控制台或文件, 可配置多个
appenders:
  stdout:
    # 控制台输出
    kind: console
    encoder:
      # 格式可配置,具体格式详见:
      # https://docs.rs/log4rs/1.0.0/log4rs/encode/pattern/index.html
      pattern: "[{h({l})}][{P}-{T}-{I}]{d(%Y-%m-%d %H:%M:%S)} - {m}{n}"
  
 # file:
    # 输出到文件
    # kind: file
    # path: logs/test.log
    # append: true
    # encoder:
    #   pattern: "{d(%Y-%m-%d %H:%M:%S)} - {m}{n}"

  rolling_file:
    # 输出到滚动文件
    kind: rolling_file
    # 日志路径
    path: logs/test.log
    # 追加模式, 即每次在已有文件末尾添加日志, 默认为 true
    append: true 
    encoder:
      pattern: "[{h({l})}][{P}-{T}-{I}]{d(%Y-%m-%d %H:%M:%S)} - {m}{n}"
    policy:
      kind: compound
      # 触发器
      trigger:
        kind: size
        limit: 100 mb
      # 分割策略
      # roller:
      #   # 删除
      #   kind: delete
      roller:
        # 固定窗口
        # 每次都往test.log中写入文件,test.log文件达到触发策略时,分割文件后移一位。
        # 即触发时,创建test.1.log文件,原test.1.log文件变为test.2.log文件,依次顺延,但只保留设置的日志数量,多余的删除。
        kind: fixed_window
        # 分割文件名称
        pattern: logs/test.{}.log
        # 从1开始
        base: 1
        # 保留*个日志
        count: 50
        
# 对全局 log 进行配置
root:
  # 配置输出的日志级别 
  # trace < debug < info < warn < error
  level: info 
  # 配置输出appender
  appenders:
    - stdout
    # rolling_file和file选一个即可
    - rolling_file

# 对特定工程进行配置,可选
loggers:
  app::backend::db:
    level: info

  app::requests:
    level: info
    appenders:
      - stdout
    # 不继承全局配置的appenders,不设置时会使用全局的appenders+自己的appenders
    additive: false

4.单元测试

//! @Author: DengLibin
//! @Date: Create in 2023-11-02 14:40:11
//! @Description: 日志测试
#[cfg(feature = "log_util")]
#[cfg(test)]
mod tests {
    use log::{trace, info, debug, warn, error};
    use rust_common::log_util;
    #[test]
    pub fn test_log(){
        let r = log_util::init_log("log4rs.yaml");
        match r {
            Ok(()) =>{
                for i in 0..50_000_u32 {
                    trace!("this is trace:{}--The following formatters are currently supported. Unless otherwise stated, a formatter does not accept any argument.", i);
                    debug!("this is debug:{}--The following formatters are currently supported. Unless otherwise stated, a formatter does not accept any argument.", i);
                    info!("this is info:{}--The following formatters are currently supported. Unless otherwise stated, a formatter does not accept any argument.", i);
                    warn!("this is warn:{}--The following formatters are currently supported. Unless otherwise stated, a formatter does not accept any argument.", i);
                    error!("this is error:{}--The following formatters are currently supported. Unless otherwise stated, a formatter does not accept any argument.", i);

                }
                
            },
            Err(err) =>{
                println!("错误:{}", err);
            }
        }
        
    }
}

关于作者

程序员,软件工程师,java, golang, rust, c, python,vue, Springboot, mybatis, mysql,elasticsearch, docker, maven, gcc, linux, ubuntu, centos, axum,llm, paddlepaddle, onlyoffice,minio,银河麒麟,中科方德,rpm