记录父类中的静态方法[英] logging static methods in a parent class

本文是小编为大家收集整理的关于记录父类中的静态方法的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个抽象的班级父,带有2个子类A和B.父有一个静态方法,称为do().我想知道,当将其称为a.do()和log b时,当将其称为b.do()时,是否有一种静态方法在logger中添加日志信息.通常的

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

无法正常工作()是一种静态方法,因此也需要静态测井,但是GetClass()方法显然不是静态的.

谢谢.

推荐答案

我不建议它,但是如果您真的想要它...

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);
  }
}

其他推荐答案

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

每个具有自己的logger的班级:指定类都可以.

其他推荐答案

最佳实践是声明logger静态,例如

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

这样,您可以使用动态和静态方法的记录器.

每个类也应具有自己的记录器实例.因此,我会将保护更改为私人.

另外,您不应该调用" getClass()",而是应该调用" myapp.class",例如

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

本文地址:https://www.itbaoku.cn/post/1575059.html

问题描述

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.

推荐答案

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);
  }
}

其他推荐答案

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

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

其他推荐答案

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);