SpringBoot AOP处理请求日志打印功能代码实例
设计原则和思路:
- 元注解方式结合AOP,灵活记录操作日志
- 能够记录详细错误日志为运营以及审计提供支持
- 日志记录尽可能减少性能影响
- 操作描述参数支持动态获取,其他参数自动记录。
代码实例如下
@Slf4j @Aspect @Configuration publicclassRequestAopConfig{ @Autowired privateHttpServletRequestrequest; privatestaticfinalThreadLocalSTART_TIME_MILLIS=newThreadLocal<>(); @Pointcut("execution(*com.xxx.xxx.xxx..*(..))"+ "&&(@annotation(org.springframework.web.bind.annotation.PostMapping)"+ "||@annotation(org.springframework.web.bind.annotation.GetMapping)"+ "||@annotation(org.springframework.web.bind.annotation.PutMapping)"+ "||@annotation(org.springframework.web.bind.annotation.DeleteMapping))") publicvoidcontrollerMethodPointcut(){ } /** *前置通知:在某连接点之前执行的通知,但这个通知不能阻止连接点之前的执行流程(除非它抛出一个异常)。 * *@paramjoinPoint参数 */ @Before("controllerMethodPointcut()") publicvoidbefore(JoinPointjoinPoint){ START_TIME_MILLIS.set(System.currentTimeMillis()); } /** *后置通知:在某连接点正常完成后执行的通知,通常在一个匹配的方法返回的时候执行。 * *@paramjoinPoint参数 */ @AfterReturning(value="controllerMethodPointcut()",returning="result") publicvoidafterReturning(JoinPointjoinPoint,Objectresult){ StringlogTemplate="---------------执行成功---------------\n请求开始---SendRequestURL:{},Method:{},Params:{}\n请求方法---ClassName:{},[Method]:{},executiontime:{}ms\n请求结束---SendResponseResult:{}"; log.info(logTemplate,request.getRequestURL(),request.getMethod(),JSON.toJSONString(joinPoint.getArgs()),joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName(),(System.currentTimeMillis()-START_TIME_MILLIS.get()),JSON.toJSONString(result)); START_TIME_MILLIS.remove(); } /** *异常通知:在方法抛出异常退出时执行的通知。 * *@paramjoinPoint参数 */ @AfterThrowing(value="controllerMethodPointcut()",throwing="ex") publicvoidafterThrowing(JoinPointjoinPoint,Throwableex){ StringlogTemplate="---------------执行失败---------------\n异常请求开始---SendRequestURL:{},Method:{},Params:{}\n异常请求方法---ClassName:{},[Method]:{},executiontime:{}ms\n异常请求结束---ExceptionMessage:{}"; log.error(logTemplate,request.getRequestURL(),request.getMethod(),JSON.toJSONString(joinPoint.getArgs()),joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName(),(System.currentTimeMillis()-START_TIME_MILLIS.get()),ex.getMessage()); START_TIME_MILLIS.remove(); } /** *最终通知。当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。 * *@paramjoinPoint */ @After("controllerMethodPointcut()") publicvoidafter(JoinPointjoinPoint){ } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。