效果
下图分别为演示方法和该方法执行完成后控制台打印的日志结果
Log Object
@DatapublicclassLogBO{/***请求URI*/privateStringrequestURI;/***方法名*/privateStringmethod;/***方法的输入*/privateObjectinput;/***方法的输出*/privateObjectoutput;/***方法耗时(ms)*/privateLongtimeConsuming;/***方法调用的时间*/privateDatedate;publicLogBO(){this.date=newDate();if(Objects.nonNull(RequestContext.getRequest())){this.requestURI=RequestContext.getRequest().getRequestURI();}}}
Annotation
@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceLog{}
Aspect
@Slf4j@Aspect@ComponentpublicclassLogAspect{@Pointcut("@annotation(com.xxx.demo.log.Log)")publicvoidlogPointCut(){//definition}@Around(value="logPointCut()")publicvoidlogAround(ProceedingJoinPointjoinPoint)throwsThrowable{LogBOlogBO=newLogBO();//getcurrentmethodMethodmethod=((MethodSignature)joinPoint.getSignature()).getMethod();logBO.setMethod(method.getDeclaringClass().getName()+"."+method.getName());Map<String,Object>input=this.getInput(joinPoint,method);logBO.setInput(input);longstartTime=System.currentTimeMillis();//getmethodreturnObjectoutput=joinPoint.proceed();logBO.setOutput(output);logBO.setTimeConsuming(System.currentTimeMillis()-startTime);log.info(JSONObject.toJSONString(logBO));}privateMap<String,Object>getInput(ProceedingJoinPointjoinPoint,Methodmethod){//getparameternamesString[]parameterNames=newDefaultParameterNameDiscoverer().getParameterNames(method);Object[]args=joinPoint.getArgs();Map<String,Object>params=newHashMap<>(8);if(parameterNames!=null&¶meterNames.length!=0){for(inti=0;i<parameterNames.length;i++){params.put(parameterNames[i],args[i]);}}returnparams;}}
Util
publicclassRequestContext{publicstaticHttpServletRequestgetRequest(){ServletRequestAttributesrequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();returnObjects.isNull(requestAttributes)?null:requestAttributes.getRequest();}}
作者:冰山邮轮