SpringBoot使用AOP记录日志本文转载请联系吴佩轩公众号。往往在项目开发中,日志系统是必不可少的,尤其是管理系统,重要的操作都会有操作日志,但是这个操作不需要我们在相应的方法中一一实现,这肯定是不合适的,这样的操作无疑增加了开发量且不易维护,所以在实际项目中总是使用AOP(AspectOrientedProgramming)来记录系统中的操作日志。下面介绍在SpringBoot中使用AOP记录日志的方法:添加依赖首先添加AOP依赖:org.springframework.bootspring-boot-starter-aopCreatealogannotationclassCreatealogannotationclass,这样就可以在需要记录日志的方法上添加注解来记录日志。注解内容如下:@Target({ElementType.PARAMETER,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceAopLogger{Stringdescribe()default"";}配置AOP切面定义一个AopLoggerAspect切面类,并使用@Aspect将此类声明为切面类。@ComponentpublicclassAopLoggerAspect{privatefinalLoggerlogger=LoggerFactory.getLogger(this.getClass());@Pointcut("@annotation(com.wupx.aop.logger.annotation.AopLogger)")publicvoidaopLoggerAspect(){}/***环触发**@parampoint*@return*/@Around("aopLoggerAspect()")publicObjectdoAround(ProceedingJoinPointpoint){RequestAttributesrequestAttributes=RequestContextHolder.getRequestAttributes();ServletRequestAttributesservletRequestAttributes=(ServletRequestAttributes)requestAttributes;HttpServletRequestrequest=servletRequestAttributes.getRequest();Objectresult=null;longstartTime=System.currentTimeMillis();try{result=point.proceed();}catch(Throwablethrowable){throwable.printStackTrace();logger.error(throwable.getMessage());}Stringdescribe=getAopLoggerDescribe(point);if(StringUtils.isBlank(describe)){describe="-";}//打印请求相关参数logger.info("==========================================开始========================================&曲ot;);logger.info("Describe:{}",describe);//打印请求urllogger.info("URL:{}",request.getRequestURL());logger.info("URI:{}",request.getRequestURI());//打印Httpmethodlogger.info("HTTPMethod:{}",request.getMethod());//打印调用控制器和执行方法的完整路径logger.info("ClassMethod:{}.{}",point.getSignature().getDeclaringTypeName(),point.getSignature().getName());//打印请求的IPlogger.info("IP:{}",request.getRemoteAddr());//打印请求输入参数logger.info("RequestArgs:{}",point.getArgs());//打印请求输出参数logger.info("ResponseArgs:{}",result);logger.info("TimeConsuming:{}ms",System.currentTimeMillis()-startTime);logger.info("=============================================结束=============================================");returnresult;}/***获取注解中方法的描述信息**@paramjoinPoint切点*@returndescribe*/publicstaticStringgetAopLoggerDescribe(JoinPointjoinPoint){MethodSignaturesignature=(MethodSignature)joinPoint.getSignature();Methodmethod=signature.getMethod();AopLoggercontrollerLog=method.getAnnotation(AopLogger.class);returncontrollerLog.describe();}}其中“@Pointcut”是定义一个切点后面跟着一个表达式,可以定义作为某个包下的方法,或者自定义注解等。@Around是在切入点前后编织代码,可以自由控制切入点何时执行。测试接下来编写Controller层进行测试:@RestController@RequestMapping("/user")@RequestBodyUseruser){UserEntityuserEntity=newUserEntity();BeanUtils.copyProperties(user,userEntity);returnuserService.addUser(userEntity);}}只需要在界面填写@AopLogger即可记录操作日志。启动服务,通过PostMan请求http://localhost:8080/user接口。输出日志如下:可以看到输入参数、输出参数和接口信息都被记录了下来。是不是很简单?只需要简单的AOP日志,几步就可以实现,大家可以自己动手实践。本文完整代码在https://github.com/wupeixuan/SpringBoot-Learn的aop-logger目录下。