Log4j: How to enable logging in a subclass for a method in a superclass

I have a registration operator in my Superclass method. I want to include this operator only if the method is called for the SubClassA object.

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 to 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

+4
source share
2 answers

I do not think this is possible because the registrar does not know anything about classes and inheritance. The registrar name is a simple text name, such as "abcd". Perhaps you could use a subclass class in a superclass, i.e. Instead:

 private static Logger logger = Logger.getLogger(SuperClass.class); 

using:

 private Logger logger = Logger.getLogger(getClass()); 

or you can use both:

 private Logger subLogger = Logger.getLogger(getClass()); private static Logger logger = Logger.getLogger(SuperClass.class); 

and then you can use more complex logic:

 if(logger.isInfoEnabled() || subLogger.isInfoEnabled()) { ... } 

But if I were you, I would not use this magic, because registration should be as simple as possible (but not simple).

+5
source

If you want to enable logging in this subclass, you must define a logger (or an additional logger for a standard package / class named one) for a specific line ( Logger.getLogger("SpecialSubClassALogger") and use it in SuperClass to be logged. Then you can use log4j.logger.SpecialSubClassALogger=info .

0
source

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


All Articles