【发布时间】:2016-07-25 11:15:10
【问题描述】:
我正在尝试在 Google - Guice 中实现基于 AOP 的日志记录。我为此使用了MethodInterceptor,但它不起作用。我通过定义切入点在 Spring 中使用了相同的方法。那里一切正常。
基于 AOP 的日志记录的 Spring 代码 -
@Aspect
public class LoggingAspect {
private static Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
@Around("requiredLog()")
public Object bentoBoxAround(ProceedingJoinPoint proceedingJoinPoint) {
Object returnValue = null;
try {
logger.info("Entered into the method -> " + proceedingJoinPoint.getSignature().toShortString()
+ " and input arguments are -> " + Arrays.asList(proceedingJoinPoint.getArgs()));
returnValue = proceedingJoinPoint.proceed();
logger.info("Method Execution over !! " + proceedingJoinPoint.getSignature().toShortString());
} catch (Throwable e) {
logger.error("Method has an exception " + e.getMessage());
}
return returnValue;
}
@Pointcut("within(org.cal.bento..*)")
public void allRequiredPakageLog() {
}
}
从上面的代码我们可以记录org.cal.bento.*包中所有的类和方法的执行。
基于 AOP 的日志记录的 Guice 代码 -
public class GuiceLoggingInterceptor implements MethodInterceptor {
private static Logger logger = LoggerFactory
.getLogger(GuiceLoggingInterceptor.class);
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object returnValue = null;
try {
logger.info("GUICE - Entered into the method -> " + invocation.getMethod().getName()
+ " and input arguments are -> " + Arrays.asList(invocation.getArguments()));
returnValue = invocation.proceed();
logger.info("Method Execution over !! " + invocation.getMethod().getName());
} catch (Throwable e) {
logger.error("GUICE - Method has an exception " + e.getMessage());
}
return returnValue;
}
}
绑定类 -
public class GuiceAopModule extends AbstractModule {
@Override
protected void configure() {
bindInterceptor(Matchers.any(), Matchers.any(), new GuiceLoggingInterceptor());
}
}
我们可以在 Guice 中做类似的日志记录吗(通过为整个日志记录系统只定义一个基于 Aspect 的类)。我不想修改每个类。
参考教程 - https://schakrap.wordpress.com/2009/07/30/method-entry-exit-logging-in-guice-with-aop/
任何帮助将不胜感激。
【问题讨论】:
-
“我已经为此使用了 MethodInterceptor 但它不起作用”。预期的输出是什么?
-
我想记录一个包内的所有方法执行。我使用的这段代码很好,但不会锁定日志文件中的任何日志。
-
您的对象是如何创建的?仅当 Guice 正在创建您要拦截的所有实例时,使用 guice 的方法拦截才有效。
-
您的日志记录配置可能有问题吗?从根本上说,您的代码应该可以正常工作。
-
@pandaadb,我在我的项目中同时使用 spring 和 guice,spring 为 guice 创建对象。
标签: java logging aop aspectj guice