zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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

2023-03-15 22:08:18 时间

注解:

@Target({METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodLog {
    /**
     * 请求是否打日志
     * @return
     */
    boolean reqLog() default true;

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

}

aop:

@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;
    }
}