How to set a static variable in each class?

I am trying to make something very simple. I have a class com.mypackage.Logger logger, the instance operator of which I would like to "insert" into each individual class: private static Logger LOG = new Logger(Class.class) . Then I would like to write each instance of the record and exit for each individual 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 is working correctly. I get the correct input and the presence of the log statements exactly as expected. The problem is that the log class associated with each log entry is incorrect. I use log4j and each log entry is formatted like this:

[TRACE] (date and time stamp) (log class name) (stream name) (some registration instruction)

The problem is that the logging class used in the instance of the Logger does not match the correct one denoted by thisJoinPoint.getSignature().getDeclaringTypeName() .

I know that I am not doing anything appropriate regarding the Logger static variable, so please help me. thank you for your time!

+4
source share
1 answer

It's simple

Your LOG attribute is defined as closed static . Static means a class attribute, not an instance attribute.

This clearly contradicts the instanciation model of your aspect, which is pertypewithin (one instance of the aspect created for each type).

Try removing the static modifier.

By the way, the definition of pertypewithin () * is quite large, you can limit the correspondence with pertypewithin (classes ())

As for the magazine, I did some experiments with AspectJ using the instanciation model and inter-type declarations. I would recommend an implementation using an inter-type declaration, because it saves more memory:

Entering a logger with perthis

Entering a logger with declaration between type

+2
source

Source: https://habr.com/ru/post/1394748/


All Articles