I have a class A which declare a static logger instance and then used in the method of the class.
class A {
static Log log = LogFactory.getLog(A.class);
person p = new Person();
public void methodA(){
// log.info("logging using apache commons logger");
}
}
I have another class B which is @Aspect type. Its method may trigger based on execution of A's method.
@Aspect
class B{
@Before(--execution of methodA() pointcut expression--)
public void methodB(JoinPoint jp){
// How to get the class A's logger instance to continue logging from same logger instance. As it will print class name A in logs
}
}
I want to use the logger instance used in class A to log some message.
How can I get the object's state in Aspect class from joinPoint with reflection.
I am not using spring framework, trying with aspectjrt apectweaver jars
You can either use
jp.getTarget()to get the target instance for a non-static method or simply bindtarget(targetObject)to an advice method parameter. I am showing you the latter. Here is my MCVE:Log4J configuration:
Helper class:
Driver application class:
Aspect:
Console log:
This kind of reflection stuff is quite ugly and might not work the way you wish in JMS-style modular applications without configurative precautions, if aspect and target class are not in the same module. At least, you could make your loggers public in order to avoid using
field.setAccessible(true).