码迷,mamicode.com
首页 > 其他好文 > 详细

AOP记录日志

时间:2019-12-17 22:05:00      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:top   let   ota   操作日志   ant   context   object   val   log   

1.自定义注解

@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented //生成文档
public @interface RptLog {
    String value() default "";
}

2.aop相关的配置类

@Slf4j
@Aspect
@Component
public class RptOperateLogAspect {

    @Autowired
    @SuppressWarnings("all")
    private RptOperateLogMapper rptOperateLogMapper;

    @Autowired
    private UserService userService;
    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation(com.in.g.data.config.RptLog)")
    public void logPoinCut() {
    }

    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        System.out.println("报表系统记录操作日志");
        //保存日志
        RptOperateLog rptOperateLog = new RptOperateLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取当前用户操作信息
        Object[] args = joinPoint.getArgs();
        if (ArrayUtils.isNotEmpty(args)){
            Integer id = (Integer) args[0];
            //记录操作用户的信息
            SessionUserDTO user = userService.getUser(id);
            rptOperateLog.setRole(user.getRoleName());
            rptOperateLog.setUsername(user.getFullName());
            rptOperateLog.setAccount(user.getUserName());
        }
        RptLog rptLog = method.getAnnotation(RptLog.class);
        if (rptLog != null) {
            String value = rptLog.value();
            //操作名称
            rptOperateLog.setOperateContent(value);
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //操作时间
        rptOperateLog.setOperateTime(new Date());
        //操作用户ip地址
        rptOperateLog.setIpAddress(IpAddressUtil.getIpAddr(request));
        //操作设备信息
        String deviceInfo = AgentUserKit.getDeviceInfo(request);
        rptOperateLog.setDevice(deviceInfo);
        //保存操作日志
        rptOperateLogMapper.saveLog(rptOperateLog);
        log.info("报表日志保存成功 rptOperateLog:[{}]",rptOperateLog);
    }
}

3.使用自定义注解

    @GetMapping("/customer_info")
    @RptLog(value = "下载-客户详情报表")
    public Result customerInfoExcelGenerate(@RequestHeader(CommonConstant.X_OPERATOR_ID) Integer loginId,
                                            @Validated  CustomerInfoDTO customerInfoDTO) {
        iReportExcelRecordService.customerInfoExcelGenerate(loginId,customerInfoDTO);
        return Result.success(null);
    }

AOP记录日志

标签:top   let   ota   操作日志   ant   context   object   val   log   

原文地址:https://www.cnblogs.com/gabriel-y/p/12057097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!