Search code examples
javaspring-bootaspectjpointcut

AspectJ - How to log overriden method name instead of superclass method name


I have built a logger class for all my repositories, services and controllers. I am making it log every method call with the following method :

@Before("execution(* com.mdenis.tno..controller..*(..)) || " + 
        "execution(* com.mdenis.tno..service..*(..)) || " + 
        "execution(* com.mdenis.tno..repository..*(..))")
private void logMethodCallWithParameters(JoinPoint joinPoint)
{
    String arguments = "";

    for (Object argument : Arrays.asList(joinPoint.getArgs()))
    {
        arguments = arguments + argument.toString() + ", ";
    }

    if (arguments.contains(", "))
    {
        arguments = arguments.substring(0, arguments.lastIndexOf(","));
    }

    if (arguments.compareTo("") == 0)
    {
        logger.debug("Method " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() 
            + " called with no argument");
    }
    else
    {
        logger.debug("Method " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() 
            + " called with argument(s) " + arguments);
    }
}

This works great but my services all extend a base service that has the common methods in it. A call to a method in PostServiceImpl therefore results in the following log statement :

Method com.mdenis.tno.service.impl.BaseServiceImpl.findAllPaginated returning with result Page 1 of 2 containing com.mdenis.tno.model.Post instances.

I would like to know if there is a way for the extending class name (PostServiceImpl) to be logged instead of the superclass name (BaseServiceImpl).

Thanks!


Solution

  • You use

    joinPoint.getTarget().getClass().getCanonicalName()
    

    for the class name.