使用 Spring AOP 清理记录器 [英] Logger clean up Using Spring AOP

查看:27
本文介绍了使用 Spring AOP 清理记录器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正尝试在我们的应用程序中引入通用记录器,使用 Spring AOP 来处理 catch 块下的日志语句.

We're trying to introduce generic logger in our application using Spring AOP for log statements which are under catch block.

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 Docs 后,我发现这可以使用 AfterThrowing 建议来完成.抛出后通知是如果方法通过抛出异常退出时要执行的通知.

After going through Spring Docs,I have found this can be done using AfterThrowing advice. After throwing advice is Advice to be executed if a method exits by throwing an exception.

为了做到这一点,我们将通过在 catch 块内重新抛出 Exception 来更改我们现有的异常处理代码,例如 AfterThrowing> 工作建议.

In order to do this We'll to change our existing exception handling code by re throwing Exception inside catch block something like this for AfterThrowing Advice to work.

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 并根据调用层次结构向上传播它?

Do you think is there any better solution than this rather than rethrowing Exception in catch block and propagating it upwards as per call hierarchy?

请注意,无论如何,AfterThrowing Advice 都会捕获任何引发或未检查的异常.我想要做的就是通过删除 catch 块中的 log.error 来执行记录器清理,并使用 AOP 使其通用.

Note any raised or unchecked exceptions would be catched anyway by AfterThrowing Advice..All i want to do is perform logger clean up by removing log.error inside catch block and have it generic using AOP.

推荐答案

正如这里所讨论的,@AfterThrowing 非常适合记录实际上抛出的异常.

As was discussed here, @AfterThrowing is nice for logging exceptions which are actually thrown.

您的案例非常特殊,因为您想记录正在捕获/处理的异常.如果您使用完整的AspectJ 对于此用例,您可以使用 handler(*) 切入点代替 Spring AOP,如 这个答案.它将使您能够从 catch 块中提取日志语句,而无需升级(重新抛出)已经正确处理的异常,从而改变您的逻辑并使其有必要捕获它们稍后在其他地方.

Your case is quite special as you want to log exceptions which are being caught/handled. If you 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. It would enable you to factor out your log statements from your catch blocks without the need to escalate (re-throw) exceptions which have already been properly handled, thus changing your logic and making it necessary to catch them somewhere else later.

这篇关于使用 Spring AOP 清理记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆