Search code examples
springspring-bootlog4jaopspring-aop

Define class name in AOP Logger


Can you tell me if it possible over Spring Boot AOP Logger define in console package and class name which is actual proxied?

For better understanding here is screenshot of my console:

enter image description here

As you can see there is package and class name of my logger, but my goal is have instead c.s.b.c.MyAspectOrientedLogger for example this c.s.b.s.UserService

And my Logger:

@Aspect
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class MyAspectOrientedLogger {

    private Logger lgr = LoggerFactory.getLogger(this.getClass());

    @Around("...")
    public Object logFunctions(ProceedingJoinPoint joinPoint) throws Throwable {

        Object proceed = joinPoint.proceed();
        LOGGER.debug("My some logging output ...");
        return proceed;
    }

I know that I can use joinPoint.getTarget().getClass() and print that name, but I want it instead logger class. Is it possible? Thanks


Solution

  • Yes, it's possible. The joinPoint argument offers a method called getSignature, which again offers the method getDeclaringType, which returns the class object of the class of the method, where that aspect was wrapped around.

    You can use it like this:

        Class type = joinPoint.getSignature().getDeclaringType();
    
        Logger lgr = LoggerFactory.getLogger(type);
    
        Object proceed = joinPoint.proceed();
        lgr.error("My some logging output ...");
    

    Result of this is however, that you can't get the logger statically, you have to obtain the instance from the factory in the aspect itself. I'm not sure about performance drawbacks in a solution like this, you would have to test it if you write a heavy load application.