AOP實現日誌記錄方法引數與返回值
阿新 • • 發佈:2020-12-17
1、annotation
/**
* 自動列印方法周邊資訊,包括引數,返回值,等等
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogMethod {
}
2、aspect
@Aspect @Slf4j @Component public class LogMethodAspect { @Pointcut("@annotation(cn.***.aspect.annotation.LogMethod)") public void logMethodAnnotation() { } @Around("logMethodAnnotation() && @annotation(logMethod)") public Object sysExceptionCatchAndProcess(ProceedingJoinPoint joinPoint, LogMethod logMethod) throws Throwable { this.logBeforeProceed(joinPoint, logMethod); Object result = joinPoint.proceed(); this.logAfterProceed(joinPoint, logMethod, result); return result; } private void logBeforeProceed(ProceedingJoinPoint joinPoint, LogMethod logMethod) { StringBuilder logBuilder = new StringBuilder(); // 方法 MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); logBuilder.append("方法引數日誌。方法:"); this.appendMethodPath(logBuilder, methodSignature); // 引數名,引數值 String[] argNames = methodSignature.getParameterNames(); Object[] args = joinPoint.getArgs(); if (args != null && args.length > 0) { logBuilder.append("引數:"); } for (int i = 0; i < argNames.length; i++) { logBuilder.append(argNames[i]).append("=").append(JSONObject.toJSONString(args[i])); } log.debug(logBuilder.toString()); } private void logAfterProceed(ProceedingJoinPoint joinPoint, LogMethod logMethod, Object result) { StringBuilder logBuilder = new StringBuilder(); // 方法 MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); logBuilder.append("方法返回日誌。方法:"); this.appendMethodPath(logBuilder, methodSignature); logBuilder.append("返回=").append(JSONObject.toJSONString(result)); log.debug(logBuilder.toString()); } private void appendMethodPath(StringBuilder stringBuilder, MethodSignature methodSignature) { stringBuilder.append(methodSignature.getMethod().getDeclaringClass().toString()) .append(".") .append(methodSignature.getMethod().getName()) .append(" "); } }