AspectJ logs with Log4j

2019-09-13 12:11发布

问题:

I am trying to implement AspectJ logging to module to analyze it better. My application is already using log4J framework.
If I run AspectJ class in a separate application it works fine but it doesn't work when I integrate it with application. Here what I have done
applicationContext.xml

<aop:aspectj-autoproxy/>
<bean id="logAspectj" class="com.test.aspect.LoggingAspect"/>

LoggingAspect class

@Component
@Aspect
public class LoggingAspect {

    private final Log log = LogFactory.getLog(this.getClass());

    @Around("execution(public void com.db.TestMarshaller.saveDoc(..))")
    public Object logTimeMethod(ProceedingJoinPoint joinPoint) throws Throwable {

            StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            Object retVal = joinPoint.proceed();

            stopWatch.stop();

            StringBuffer logMessage = new StringBuffer();
            logMessage.append(joinPoint.getTarget().getClass().getName());
            logMessage.append(".");
            log.info(logMessage.toString());
            return retVal;
    }

}

Note: Here TestMarshaller is not exposed via Spring.

Is there some specific AspectJ setting for Log4j?

回答1:

since your com.db.TestMarshaller is not "spring managed" (there is no Spring bean of that type in your context), the used spring namespace will NOT create a proxy which calls your Aspect.

In this case you'll either have to compile your sources with the AspectJ Compiler (Compile Time Weaving) or use the aspectj runtime to modify your bytecode when your class is loaded (Load Time Weaving).

It really depends on your use case which way you go - if your Aspect is part of your business logic and can not change during runtime, use the aspectj compiler, since it will only be done once. I case you need a more dynamic application of your aspect, use load time weaving instead.

Hope this helps, Jochen