基于aop的注解对方法调用前后打日志

2021-11-22 09:43:08 浏览数 (1)

注解:

代码语言:javascript复制
@Target({METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodLog {
    /**
     * 请求是否打日志
     * @return
     */
    boolean reqLog() default true;

    /**
     * 返回是否打日志
     * @return
     */
    boolean respLog() default true;

}

aop:

代码语言:javascript复制
@Aspect
@Component
@Slf4j
public class MethodLogAop {

    @Around("@annotation(MethodLog)")
    public Object methodLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("before invoke: "   System.currentTimeMillis()   ","
                  joinPoint.getSignature().getDeclaringTypeName()   "."   joinPoint.getSignature().getName()   ", requests : "
                  JSON.toJSONString(Arrays.asList(joinPoint.getArgs()),
                SerializerFeature.DisableCircularReferenceDetect));
        Object obj;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable e) {
            log.error("exception invoke: "    System.currentTimeMillis()   ","
                      joinPoint.getSignature().getDeclaringTypeName()   "."   joinPoint.getSignature().getName()   "exception: "
                      e.getMessage());
            throw e;
        }
        log.info("after invoke: "    System.currentTimeMillis()   ","
                  joinPoint.getSignature().getDeclaringTypeName()   "."   joinPoint.getSignature().getName()   ", response : "
                  JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect));
        return obj;
    }
}

0 人点赞