项目进入集成测试阶段后,调试的时候有个问题:
主要代码:
拦截器:
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class InoutLogger implements MethodInterceptor {
private final Logger logger = LoggerFactory.getLogger(InoutLogger.class);
private boolean isPrint = true;
public boolean getIsPrint() {
return InoutLogger.isPrint;
}
public void setIsPrint(boolean isPrint) {
InoutLogger.isPrint = isPrint;
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
if (isPrint) {
return this.invokeWithLogging(mi);
} else {
return mi.proceed();
}
}
private Object invokeWithLogging(MethodInvocation mi) throws Throwable {
long startTime = System.currentTimeMillis();
Object obj = invokeMethod(mi);
logger.info("invokeMethod: {}, elapsed time (ms): {}", mi.getMethod().getName(), (System.currentTimeMillis() - startTime));
Object[] args = mi.getArguments();
if (null != args && args.length > 0) {
for (int i = 0; i < args.length; i++) {
logger.info("args[{}]: {}" ,i, args[i]);
}
}
logger.info("returns:{}", obj);
return obj;
}
}
用于标识需要拦截类的annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface InoutLogging {
}
拦截器的使用:
bindInterceptor(Matchers.annotatedWith(InoutLogging.class), Matchers.any(), new InoutLogger());
发生bug时,因为问题发生时环境的复杂性,输入、输出难以复现。
这个问题是一个典型的AOP应用场景。
使用AOP,可以在有2个方面提高工程效率:
1.统一处理输入、输出log,解耦参数log模块与具体的业务模块,避免在每个方法调用中写一堆逻辑相似的手动添加log代码,参数log模块有变更时不用逐个修改手工写的log代码,提高整个系统的可维护性;
2.保证log输出格式的统一性,方便编写自动化工具分析日志、自动报警,提高系统维护效率。
题外话:其它适合使用aop的场景,也都能从上面2个方面得到工程效率的提升。
主要代码:
拦截器:
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class InoutLogger implements MethodInterceptor {
private final Logger logger = LoggerFactory.getLogger(InoutLogger.class);
private boolean isPrint = true;
public boolean getIsPrint() {
return InoutLogger.isPrint;
}
public void setIsPrint(boolean isPrint) {
InoutLogger.isPrint = isPrint;
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
if (isPrint) {
return this.invokeWithLogging(mi);
} else {
return mi.proceed();
}
}
private Object invokeWithLogging(MethodInvocation mi) throws Throwable {
long startTime = System.currentTimeMillis();
Object obj = invokeMethod(mi);
logger.info("invokeMethod: {}, elapsed time (ms): {}", mi.getMethod().getName(), (System.currentTimeMillis() - startTime));
Object[] args = mi.getArguments();
if (null != args && args.length > 0) {
for (int i = 0; i < args.length; i++) {
logger.info("args[{}]: {}" ,i, args[i]);
}
}
logger.info("returns:{}", obj);
return obj;
}
}
用于标识需要拦截类的annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface InoutLogging {
}
拦截器的使用:
bindInterceptor(Matchers.annotatedWith(InoutLogging.class), Matchers.any(), new InoutLogger());