I am trying to do something very simple. I have a com.mypackage.Logger logger class whose instantiation statement I would like to “insert” into every single class like so: private static Logger LOG = new Logger(Class.class). Then, I would like to log every single entry and exit instance for every single function in my project. Here is my aspect:
public aspect LoggingAspect pertypewithin(*) {
private static Logger LOG;
pointcut classes(): within(com.mypackage..*) && !within(com.mypackage.Logger) && !within(com.mypackage.LoggingAspect);
pointcut functions(): classes() && (execution(* *(..)) || execution(new(..)));
before(): staticinitialization(*) && classes() {
LOG = new Logger(thisJoinPointStaticPart.getSignature().getDeclaringType());
}
before() : functions() {
LOG.trace("ENTER " + thisJoinPoint.getSignature().toLongString());
}
after() returning(@SuppressWarnings("unused") Object ret) : functions() {
LOG.trace("EXIT " + thisJoinPoint.getSignature().toLongString());
}
Almost everything works properly. I am getting correct enter and exist log statements exactly as expected. The problem is that the logging class that is associated with each log entry is incorrect. I am using log4j, and each log entry is formatted like so:
[TRACE] (date and time stamp) (logging class name) (thread name) (some logging statement)
The problem is that the logging class used in Logger instantiation does not match the correct one that is indicated by thisJoinPoint.getSignature().getDeclaringTypeName().
I know that I am not doing something right with respect to the static Logger variable, so please help me. thank you for your time!!!
It’s simple
Your LOG attribute is defined as private static. Static means that’s a class attribute, not instance attribute.
This is clearly contradicting the instanciation model of your aspect, which is pertypewithin (one instance of aspect created for each type).
Try to remove the static modifier.
By the way, defining pertypewithin()* is quite large, you can restrict down the matching with pertypewithin(classes())
For the logging stuff, I’ve done some experimentations with AspectJ using instanciation model & inter-type declarations. I would advise the implementation using inter-type declaration because it is more memory-saving:
Logger injection with perthis
Logger injection with inter-type declaration