Spring - slf4J:如何自动记录错误和异常?
我们将 Spring 与 slf4j 和 hibernate 一起使用,我试图找到一种自动记录异常和错误的方法(即无需在每个类中启动调试器的实例),以便它可以捕获任何抛出的错误或异常在日志中获取类和方法名称,
我读了一篇关于使用方面和方法的简短说明;为此拦截器,所以你能为我提供一些详细的方法来实现这一点,
问候,
We are using Spring with slf4j and hibernate, I'm trying to figure out a way to log exceptions and errors automatically (i.e without initiating an instance of the debugger in each class), so that it may catch any error or exception thrown and also get class and method name in the log,
I read a very short note about using aspects & interceptors for this, so could you provide me with some detailed way to implement this,
Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
异常方面可能如下所示:
spring conf:
编辑:
如果您希望记录器代表包装的 bean 进行记录,您当然可以这样做:
或者如果您更喜欢此方法的声明类而不是实际的(可能代理的) /自动生成类型):
老实说,我无法估计每次调用 LoggerFactory.getLogger(..) 的性能影响。我认为这应该不会太糟糕,因为无论如何,例外都是例外的(即罕见的)。
an exception aspect could look like this:
spring conf:
EDIT:
if you want the logger to log on behalf of the wrapped bean, you could of course do:
or if you prefere the declaring class of this method rather than the actual (potentially proxied/auto-generated type):
Honestly, I can't estimate the performance implications of calling LoggerFactory.getLogger(..) every time. I'd assume that it shouldn't be too bad, as exceptions are exceptional (i.e. rare) anyway.
使用纯 Aspect J(您也可以将它用于非 spring 管理的 bean)。
此示例记录服务方法“返回”的所有异常。但是您也可以更改它与其他方法匹配的切入点。
它是为 JUnit 编写的,但您可以轻松地适应它。
With pure Aspect J (than you can use it for not spring managed beans too).
This excample loggs all exceptions "returned" by a service method. But you can change the pointcut that it matches other methods too.
It is written for JUnit, but you can easely adapt it.