logging static methods in a parent class

僤鯓⒐⒋嵵緔 提交于 2019-12-12 20:41:06

问题


I have an abstract class Parent, with 2 subclasses A and B. Parent has one static method called do(). I am wondering if there is a way for that static method to add log info in Logger for class A when it's called as A.do() and log B when it's called as B.do(). The usual

protected final Logger LOGGER = Logger.getLogger(getClass());

won't work as do() is a static method so Logger needs to be static as well, but the getClass() method is obviously not static.

Thanks.


回答1:


I wouldn't recommend it, but if you really want it...

public class A {
  public static void do() {
    doImpl(A.class);
  }
  protected static void doImpl(Class<?> refClass) {
  }
}

public class B extends A {
  public static void do() {
    doImpl(B.class);
  }
}



回答2:


private final static Logger LOGGER = Logger.getLogger(A.class);

Every class having its own logger: specifying the class is fine.




回答3:


Best practice is to declare LOGGER static, e.g.

protected final static Logger LOGGER = Logger.getLogger(getClass());

This way you can use LOGGER from dynamic and static methods.

Also each class should have its own instance of the logger. So I would change protected to private.

ALSO, instead of calling "getClass()" you should call "MyApp.class", e.g.

private final static Logger LOGGER = Logger.getLogger(MyApp.class);


来源:https://stackoverflow.com/questions/15571950/logging-static-methods-in-a-parent-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!