How to automatically log the entry/exit of methods in Java?

I suggest the use of Aspect Oriented Programming.

For example, using the AspectJ compiler (which can be integrated to Eclipse, Emacs and others IDEs), you can create a piece of code like this one:

aspect AspectExample {
    before() : execution(* Point.*(..))
    {
         logger.entering(thisJoinPointStaticPart.getSignature().getName(), thisJoinPointStaticPart.getSignature().getDeclaringType()   );

    }

    after() : execution(* Point.*(..))
    {
         logger.exiting(thisJoinPointStaticPart.getSignature().getName() , thisJoinPointStaticPart.getSignature().getDeclaringType()  );

    }
}

This aspect adds a logging code after and before the execution of all methods in the class “Point”.

Leave a Comment