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 "abcd". Maybe you could use subclass's class in super class, ie 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).
如果您只想在这个子类中启用日志记录,则应将记录器(或标准软件包/类名为one的其他记录器)定义为特定字符串( Logger.getLogger("SpecialSubClassALogger")
并在SuperClass
使用它来记录然后,您可以使用log4j.logger.SpecialSubClassALogger=info
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.