AOP实现系统日志功能

1.pom文件
        <!-- Aop BEGIN -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!-- Aop END -->
2.自定义日志注解
/**
 * 
* @ClassName: SysLog
* @Description: 系统日志注解
* @author chenliqiao
* @date 2018年5月23日 上午10:12:46
*
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SysLog {
    
    /**
     * 模块
     */
    String module() default "";
    
    /**
     * 操作类型
     */
    String type() default "";
    
    /**
     * 操作名称
     */
    String name() default "";
}
3.Aspect日志切面
/**
 * 
* @ClassName: SysLogAspect  
* @Description: 系统日志切面
* @author chenliqiao
* @date 2018年5月23日 下午12:00:17
*
 */
@Aspect
@Component
@EnableAspectJAutoProxy
public class SysLogAspect {
    
    @Resource
    protected JsonRedisUtil redisUtil;
    
    @Resource
    private SysLogInfoService sysLogInfoService;
    
    /**
     * 注解声明切点
     */
    @Pointcut("@annotation(cn.net.infinite.amms.common.annotation.SysLog)")
    public void annotationPointCut(){       
    }
    
    /**
     * 环绕通知
     */
    @SuppressWarnings("unchecked")
    @Around("annotationPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        Object result=joinPoint.proceed();
        
        //方法执行失败,则直接返回
        Result<Object> response=(Result<Object>) result;
        if(!ResultCode.SUCCESS_CODE.equals(response.getRetCode()))
            return result;
        
        //保存系统日志
        this.saveSysLog(joinPoint, result);
        
        return result;
    } 
    
    /**
     * 保存系统日志信息
     */
    private void saveSysLog(ProceedingJoinPoint joinPoint,Object result){
        SysLogInfo entity=new SysLogInfo();
        
        //设置操作人信息
        CurrentUserInfo currentUser=this.redisUtil.string_get(AdminInfoUtil.getCurrentToken(), CurrentUserInfo.class);
        if(currentUser!=null){
            entity.setOperatorId(currentUser.getBaseInfo().getId());
            entity.setOperator(currentUser.getBaseInfo().getName());
        }
        entity.setOperatorTime(new Date());
        
        //获取系统日志注解,并设置操作类型和操作描述
        MethodSignature signature=(MethodSignature) joinPoint.getSignature();
        SysLog sysLog=signature.getMethod().getAnnotation(SysLog.class);
        entity.setModule(sysLog.module());
        entity.setType(sysLog.type());
        entity.setTitle(sysLog.name());
        
        //请求参数和返回结果
        List<Object> params=new ArrayList<>();
        for (Object param : joinPoint.getArgs()) {
            //上传文件格式,只记录文件名
            if(param instanceof MultipartFile){
                MultipartFile file=(MultipartFile) param;
                params.add(file.getOriginalFilename());
                continue;
            }
            params.add(param);  
        }
        entity.setReqParam(JsonUtil.beanToJson(params));
        entity.setResult(JsonUtil.beanToJson(result));
        
        //持久化到库
        this.sysLogInfoService.add(entity);
    }
}
4.数据库日志表
CREATE TABLE `sys_log_info` (
  `sl_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `module` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '模块名称',
  `type` varchar(10) COLLATE utf8_bin DEFAULT NULL COMMENT '类型',
  `title` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '标题',
  `req_param` text COLLATE utf8_bin COMMENT '请求参数',
  `result` text COLLATE utf8_bin COMMENT '返回结果',
  `operator_id` int(11) DEFAULT NULL COMMENT '操作人id',
  `operator` varchar(20) COLLATE utf8_bin DEFAULT NULL COMMENT '操作人',
  `operator_time` datetime DEFAULT NULL COMMENT '操作时间',
  PRIMARY KEY (`sl_id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
4.使用实例
/**
     * 新增
     */
    @ApiOperation(value="用于新增用户")
    @RequestMapping(value="/user/add",method=RequestMethod.POST)
    @LoginRequire
    @SysLog(type="新增",name="新增用户",module="用户管理")
    public Result<Object> add(@RequestBody UserInfoAdd request){
        this.userInfoService.add(request);
        return new Result<>();
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,935评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,859评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,977评论 25 708
  • mac 终端 常用命令基本命令1、列出文件ls 参数 目录名 例: 看看驱动目录下有什么:ls /S...
    Zhui_Do阅读 585评论 0 5
  • 色彩不够梦幻,黄色太深了
    清晓远阅读 295评论 0 0