Reputation: 123
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
Upvotes: 4
Views: 5199
Reputation: 1392
If you only want to enable logging in this one subclass you should define the logger (or an additional logger to the standard package/class named one) to a specific string (Logger.getLogger("SpecialSubClassALogger")
and use it in SuperClass
to log. You can then use log4j.logger.SpecialSubClassALogger=info
.
Upvotes: 0
Reputation: 28951
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:
private static Logger logger = Logger.getLogger(SuperClass.class);
use:
private Logger logger = Logger.getLogger(getClass());
or you could use both:
private Logger subLogger = Logger.getLogger(getClass());
private static Logger logger = Logger.getLogger(SuperClass.class);
and then you could use more sophisticated logic:
if(logger.isInfoEnabled() || subLogger.isInfoEnabled())
{
...
}
But if I were you, I would not use this magic, because logging should be as simple as possible (but not simpler).
Upvotes: 5