zoukankan      html  css  js  c++  java
  • 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(" ");
        }
    }
    
  • 相关阅读:
    BZOJ-3940:Censoring(AC自动机裸题)
    BZOJ-3881:Divljak (AC自动机+DFS序+树链求并+树状数组)
    CodeForces
    CodeForces 547E:Mike and Friends(AC自动机+DFS序+主席树)
    CodeForces -163E :e-Government (AC自动机+DFS序+树状数组)
    CodeForces
    CodeForces
    BZOJ2726:任务安排(DP+斜率优化+二分)
    bzoj 2049: [Sdoi2008]Cave 洞穴勘测
    [SDOI2009]Bill的挑战
  • 原文地址:https://www.cnblogs.com/tuofan/p/14149226.html
Copyright © 2011-2022 走看看