使用 Spring AOP 清理记录器
Logger clean up Using Spring AOP
我们正尝试在我们的应用程序中引入通用记录器,使用 Spring AOP 来处理 catch 块下的日志语句。
AOP 之前
try
{
\Business Logic
}
catch(Exception e){
\some recovery mechanism that won't be generic across different layers
log.error();//These statements needs to be moved to generic logger
}
阅读 Spring 文档后,我发现这可以使用 AfterThrowing 建议来完成。
throwing advice 之后是 Advice to be executed if a method exits by throw an exception.
为了做到这一点,我们将通过在 catch
块中重新抛出 Exception
来更改我们现有的异常处理代码,这样 AfterThrowing
建议工作。
AOP 之后:
try
{
\Business Logic
}
catch(Exception e){
\some recovery mechanism that won't be generic across different layers
throw e;
}
AOP代码:
@Aspect
@Sl4j
@Component
public class LoggingAdvice {
@AfterThrowing(pointcut = "execution (* * com..*(..)", throwing = "e")
public void myAfterThrowing(JoinPoint joinPoint, Exception e) {
log.error("Exception occured",e);
}
}
除了在 catch 块中重新抛出 Exception 并按照调用层次向上传播之外,您认为还有比这更好的解决方案吗?
请注意,AfterThrowing Advice 无论如何都会捕获任何引发的或未经检查的异常。我想做的就是通过删除 catch 块内的 log.error
来执行记录器清理,并使用 AOP 使其通用。
更好的方法是删除 catch
块,因为无论如何您都将使用 @AfterThrowing
。并在该方面执行之上实现您想实现的任何东西。
正如这里讨论的那样,@AfterThrowing
非常适合记录实际上 抛出的异常 .
您的情况非常特殊,因为您想要记录 caught/handled 的异常。如果你use full AspectJ instead of Spring AOP for this use case you can use a handler(*)
pointcut as described with sample code in this answer。它将使您能够从 catch
块中提取日志语句,而无需升级 (re-throw) 已经正确处理的异常,从而改变您的逻辑并有必要在某个地方捕获它们其他稍后。
我们正尝试在我们的应用程序中引入通用记录器,使用 Spring AOP 来处理 catch 块下的日志语句。
AOP 之前
try
{
\Business Logic
}
catch(Exception e){
\some recovery mechanism that won't be generic across different layers
log.error();//These statements needs to be moved to generic logger
}
阅读 Spring 文档后,我发现这可以使用 AfterThrowing 建议来完成。 throwing advice 之后是 Advice to be executed if a method exits by throw an exception.
为了做到这一点,我们将通过在 catch
块中重新抛出 Exception
来更改我们现有的异常处理代码,这样 AfterThrowing
建议工作。
AOP 之后:
try
{
\Business Logic
}
catch(Exception e){
\some recovery mechanism that won't be generic across different layers
throw e;
}
AOP代码:
@Aspect
@Sl4j
@Component
public class LoggingAdvice {
@AfterThrowing(pointcut = "execution (* * com..*(..)", throwing = "e")
public void myAfterThrowing(JoinPoint joinPoint, Exception e) {
log.error("Exception occured",e);
}
}
除了在 catch 块中重新抛出 Exception 并按照调用层次向上传播之外,您认为还有比这更好的解决方案吗?
请注意,AfterThrowing Advice 无论如何都会捕获任何引发的或未经检查的异常。我想做的就是通过删除 catch 块内的 log.error
来执行记录器清理,并使用 AOP 使其通用。
更好的方法是删除 catch
块,因为无论如何您都将使用 @AfterThrowing
。并在该方面执行之上实现您想实现的任何东西。
正如这里讨论的那样,@AfterThrowing
非常适合记录实际上 抛出的异常 .
您的情况非常特殊,因为您想要记录 caught/handled 的异常。如果你use full AspectJ instead of Spring AOP for this use case you can use a handler(*)
pointcut as described with sample code in this answer。它将使您能够从 catch
块中提取日志语句,而无需升级 (re-throw) 已经正确处理的异常,从而改变您的逻辑并有必要在某个地方捕获它们其他稍后。