Java Logger in a subclass

To force C.run () to use its own class registrar, do I have to add the public / protected getLogger () method to B?

public abstract class A extends Thread { @Override public abstract void run(); } public class B extends A { private static final Logger logger = Logger.getLogger(B.class.getName()); @Override protected void run() { // do something logger.info("B"); } } public class C extends B { } 
+7
source share
2 answers

It’s good that Loggers are perfectly tuned at the class level. Therefore, if C needs its own Logger, then declare your own Logger in C, for example.

 private static final Logger logger = Logger.getLogger(C.class.getName()); 

Thus, when C runs some code, it logs in its own Logger, and when B runs it, it logs in its own Logger. You can clearly see which class keeps a journal in this way.

If this is not what you need, expand the question with what you are trying to achieve and why.

I'm not sure the following code is a good idea (I always want the class that physically ran the code to be Logger), but it should work:

 public abstract class A extends Thread { @Override public abstract void run(); protected abstract Logger getLogger(); } public class B extends A { private static final Logger logger = Logger.getLogger(B.class.getName()); @Override public void run() { getLogger().info("B"); } @Override protected Logger getLogger() {return logger;); } public class C extends B { private static final Logger logger = Logger.getLogger(C.class.getName()); @Override protected Logger getLogger() {return logger;); } 
+9
source

You can use this in the base class:

 protected Logger logger = Logger.getLogger(this.getClass().getName()); 

this.getClass() initializes the registrar with the subclass name.

+2
source

All Articles