AOP实现日志记录方法参数与返回值

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(" ");
    }
}
posted @ 2020-12-17 13:49  小拓同学  阅读(664)  评论(0编辑  收藏  举报