用自定义注解实现接口信息的日志打印

  • 定义注解
    import java.lang.annotation.*;
    
    
    /**
     * web日志注解
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    @Documented
    public @interface WebLog {
    
        /**
         * 日志描述信息
         *
         * @return
         */
        String description() default "";
    }
  • 注解实现类
    import com.google.gson.Gson;
    import lombok.extern.slf4j.Slf4j;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import java.lang.reflect.Method;
    import java.util.Objects;
    
    @Aspect
    @Configuration
    @Slf4j
    public class WebLogAspect {
    
        /**
         * 以自定义@WebLog注解为切点
         */
        @Pointcut("@annotation(com.experiencetex.skills.config.annotation.WebLog)")
        public void webLog() {
        }
    
        /**
         * 环绕
         *
         * @return java.lang.Object
         * @params [pjp]
         * @description
         */
        @Around("webLog()")
        public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
            long startTime = System.currentTimeMillis();
            Object result = pjp.proceed();
            if (!(result instanceof ResponseEntity)) {
                log.info("Response Args  : {}", new Gson().toJson(result));
                log.info("Time-Consuming : {}", System.currentTimeMillis() - startTime);
            }
    
            return result;
        }
    
    
        /**
         * 在切点之前记录
         *
         * @return void
         * @params [joinPoint]
         * @description
         */
        @Before("webLog()")
        public void doBefore(JoinPoint joinPoint) throws Exception {
            // 开始打印请求日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
            // 获取 @WebLog 注解的描述信息
            String methodDescription = getAspectLogDescription(joinPoint);
            // 打印请求相关参数
            log.info("======================================== Start ==========================================");
            // 打印请求 url
            log.info("URL            : {}", request.getRequestURL().toString());
            // 打印描述信息
            log.info("Description    : {}", methodDescription);
            // 打印 Http method
            log.info("HTTP Method    : {}", request.getMethod());
            // 打印调用 controller 的全路径以及执行方法
            log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
            // 打印请求的 IP
            log.info("IP             : {}", request.getRemoteAddr());
            // 打印请求入参
            log.info("Request Args   : {}", new Gson().toJson(joinPoint.getArgs()));
        }
    
        /**
         * 获取切面注解的描述
         *
         * @param joinPoint 切点
         * @return 描述信息
         * @throws Exception
         */
        public String getAspectLogDescription(JoinPoint joinPoint)
                throws Exception {
            String targetName = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            Object[] arguments = joinPoint.getArgs();
            Class targetClass = Class.forName(targetName);
            Method[] methods = targetClass.getMethods();
            StringBuilder description = new StringBuilder();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Class[] clazzs = method.getParameterTypes();
                    if (clazzs.length == arguments.length) {
                        description.append(method.getAnnotation(WebLog.class).description());
                        break;
                    }
                }
            }
            return description.toString();
        }
    }

猜你喜欢

转载自www.cnblogs.com/21-Gram/p/11274952.html
今日推荐