美文网首页Spring
AOP实现系统日志功能

AOP实现系统日志功能

作者: Allen丶Joe | 来源:发表于2018-05-24 23:42 被阅读75次
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<>();
    }

相关文章

网友评论

    本文标题:AOP实现系统日志功能

    本文链接:https://www.haomeiwen.com/subject/kxiejftx.html