I have a logging statement in a method of my Superclass. I want to enable this statement only if the method is called for an Object of SubClassA.
public class SuperClass
{
private static Logger logger = Logger.getLogger(SuperClass.class);
public void test()
{
logger.info("test...");
}
}
…
public class SubClassA extends SuperClass
{
private static Logger logger = Logger.getLogger(SubClassA.class);
}
…
public class SubClassB extends SuperClass
{
private static Logger logger = Logger.getLogger(SubClassB.class);
public static void main(String[] p_Args)
{
SubClassA subClassA = new SubClassA();
SubClassB subClassB = new SubClassB();
subClassA.test();
subClassB.test();
}
}
How do I enable logging in test() only for SubclassA?
log4j.logger.SuperClass=info //enables logging in the test() method for both Subclasses
log4j.logger.SubClassA=info //does nothing for the test() method
I don’t think it’s possible, because logger doesn’t know anything about classes and inheritance. A logger name is a simple textual name like “a.b.c.d”. Maybe you could use subclass’s class in super class, i.e. instead of:
use:
or you could use both:
and then you could use more sophisticated logic:
But if I were you, I would not use this magic, because logging should be as simple as possible (but not simpler).