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(" ");
        }
    }
    
  • 相关阅读:
    eclipse-source not found
    eclipse-[org.apache.hadoop.util.Shell]
    Oracle—字段多行合并(LISTAGG)
    Selenium IDE 命令使用——断言
    Selenium IDE录制脚本——Chrome浏览器使用介绍
    Selenium家族谱(三生三世)
    python自动化测试之多线程生成BeautifulReport测试报告
    Python接口自动化之ExtentHTMLTestRunner测试报告
    [Java] Tomcat
    [刷题] 1002 写出这个数 (20分)
  • 原文地址:https://www.cnblogs.com/tuofan/p/14149226.html
Copyright © 2011-2022 走看看