AOP记录日志
Posted gabriel-y
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AOP记录日志相关的知识,希望对你有一定的参考价值。
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记录日志的主要内容,如果未能解决你的问题,请参考以下文章