Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - slf4J : how to automatically log errors and exceptions?

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,

like image 365
Amr Faisal Avatar asked Mar 15 '11 09:03

Amr Faisal


1 Answers

an exception aspect could look like this:

@Aspect
public class ExceptionAspect {

  private static final Logger log = LoggerFactory.getLogger(ExceptionAspect.class);

  public Object handle(ProceedingJoinPoint pjp) throws Throwable {
     try {
       return pjp.proceed();
     } catch (Throwable t) {
       // so something with t: log, wrap, return default, ...
       log.warn("invocation of " + pjp.getSignature().toLongString() + " failed", t);
       // I hate logging and re-raising, but let's do it for the sake of this example
       throw t;
     }
  }
}

spring conf:

<!-- log exceptions for any method call to any object in a package called 'svc' -->
<bean class="org.example.aspects.ExceptionAspect" name="exceptionAspect" />
<aop:config>
  <aop:aspect ref="exceptionAspect">
    <aop:around method="handle" pointcut="execution(* org.example..svc..*.*(..))" />
  </aop:aspect>
</aop:config>

EDIT:

if you want the logger to log on behalf of the wrapped bean, you could of course do:

LoggerFactory.getLogger(pjp.getTarget().getClass()).warn("damn!");

or if you prefere the declaring class of this method rather than the actual (potentially proxied/auto-generated type):

LoggerFactory.getLogger(pjp.getSignature().getDeclaringType()).warn("damn!");

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.

like image 80
sfussenegger Avatar answered Nov 15 '22 05:11

sfussenegger