基于事件驱动的日志组件

200 阅读2分钟

“我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情

auto-log

介绍

这是一个基于事件驱动的自定义Java日志组件,封装了Logback,通过一个注解实现访问接口的日志采集、发布,支持扩展注入当前的操作人。可以简单的与Spring Boot 工程整合。

软件架构

  • JDK 1.8+
  • Spring
  • Spring Event
  • Logback
  • fastjson

仓库地址

gitee.com/zero-jc/aut…

安装教程

  1. 将lib中的jar安装到本地的maven仓库

    mvn install:install-file -Dfile=auto-log-1.0.0.jar -DgroupId=com.jc.log -DartifactId=auto-log -Dversion=1.0.0 -Dpackaging=jar
    
  2. 自己的工程中引入auto-log依赖

     <dependency>
         <groupId>com.jc.log</groupId>
         <artifactId>auto-log</artifactId>
         <version>1.0.0</version>
     </dependency>
    

使用说明

  1. 开启&关闭auto-log (默认开启)
   auto:
     log:
       enabled: true
  1. 自定义Logback配置文件(可选)

  2. 定义自己的日志操作类

import com.jc.log.entity.SysLog;
import org.springframework.stereotype.Service;

@Service
public class LogService {

   /**
    * 自定义日志操作方法
    * @param sysLog 日志信息对象
    */
    public void saveLog(SysLog sysLog){
        //TODO: 根据需求完成自定义日志操作(入库)
    }
}
  1. 日志监听器配置
import com.jc.log.event.SysLogListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class LogAutoConfiguration {

   /**
    * 自动配置日志监听器组件
    * @param logService 日志操作类
    * @return  日志事件监听器                  
    */
    @Bean
    @ConditionalOnMissingBean
    public SysLogListener sysLogListener(LogService logService){
        return new SysLogListener(sysLog -> {
           logService.saveLog(sysLog);
        });
    }

}
  1. 在controller接口上添加日志注解
@RestController
@RequestMapping("/log")
public class AutoLogTestController {
    
   @AutoSysLog(value = "日志", recordResponseParam = false)
   @GetMapping("/test/{id}")
   public String sayHellos(@PathVariable("id") String id, String Name) {
      return "成功";
   }
}

扩展

  • 使用组件提供的 CurrentLoginService接口的getCurrentUserInfo方法来注入当前操作人信息
  • 使用CurrentUser对象封装操作人信息(userId、username)
  • 接口提供默认的实现,返回null
  • 第三方工程实现CurrentLoginService接口,根据自身业务完成操作人信息注入
import com.jc.log.api.CurrentLoginService;
import com.jc.log.entity.CurrentUser;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class CurrentLoginServiceImpl implements CurrentLoginService {

   @Override
   public CurrentUser getCurrentUserInfo(HttpServletRequest request) {
      //TODO:根据 request 对象获取当前登录人信息
      return new CurrentUser("admin","超级管理员");
   }
}