问题描述
我有一个抽象的班级父,带有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);
问题描述
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);