[logback-user] How to handle logging in aop methods

Mandy Warren mandys.inbox at gmail.com
Fri Nov 1 18:26:21 CET 2013



Hi,

I am using AOP to log exceptions from methods after they are thrown. I have an Aspect which does the following:-

   @AfterThrowing(pointcut = "execution(* *(..))", throwing = "ex")
   public void logExceptions "(JoinPoint jp, Throwable ex) {

       Logger exceptionLogger = LoggerFactory.getLogger(jp.getStaticPart().getSignature().getDeclaringTypeName());
       exceptionLogger.error(ex.getMessage(), ex);
      }

Now, my logback config is set to log the method and line number as follows:-

%class\(%M:%L\)

This works great for classes which don't use the aspect but for the classes which throw the exception I get the method logged as "logExceptions" (ie. the method in the Aspect) and the line number of the line where the exceptionLogger.error is called.
What I really want to log is the calling class and the method which threw the exception.

So I used %logger% instead of %class% which worked great (it gave me the calling class) BUT I can't see a way to get the method from the logger (I can get it via the AOP joinpoint but that doesn't help!). Is it possible?

I also tried using %caller{2} which did work (although the line number wasn't accurate) but I'd like to remove the Caller+0 part and reformat the Caller+1 line to look the same as the output from %class\(%M:%L\) - not sure if this is possible or
whether there is a simpler way to achieve what I want

Any advice much appreciated!

Many thanks

Mandy


Sent from a mobile device


More information about the Logback-user mailing list