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(" ");
        }
    }
    
  • 相关阅读:
    配置伪静态的好处
    RewriteCond和13个mod_rewrite应用举例Apache伪静态
    什么是伪静态?伪静态有何作用?
    推荐16个下载超酷脚本的热门网站
    thinkphp 表单自动验证功能
    窗体界面设计03
    ExtJs双折线图
    课程设计之"网络考试系统"(php、Extjs)
    布局元素和用户控件设计Silverlight网站02
    Silverlight的皮肤转换和datagrid数据显示
  • 原文地址:https://www.cnblogs.com/tuofan/p/14149226.html
Copyright © 2011-2022 走看看