Java记录与抽象类 [英] Java Logging With Abstract Classes
问题描述
我正在开发一个项目,目前正在使用log4j实现一些日志记录,我很好奇我应该如何实现日志。我正在讨论的两个实现如下:
I am working on a project, and am currently working on implementing some logging with log4j and I was curious about how I should go about implementing the logs. The two implementations I am kicking around are as follows:
第一个选项
使用来自超类的单个日志用于该类和所有子类:
Use single log from super class for that class and all sub classes:
public abstract class AbstractFoo {
protected static Log LOG = LogFactory.getLog(AbstractFoo.class);
...
}
public class Foo extends AbstractFoo {
public void someMethod() {
LOG.info("Using abstract log");
}
}
第二个选项
为每个类使用单独的日志,super和subs:
Use individual logs for each class, super and subs:
public abstract class AbstractFoo {
private static Log LOG = LogFactory.getLog(AbstractFoo.class);
...
}
public class Foo extends AbstractFoo {
private static Log LOG = LogFactory.getLog(Foo.class);
public void someMethod() {
LOG.info("Using own log");
}
}
什么更有意义?为什么?
What makes more sense and why?
推荐答案
我也不愿意。相反,我会在两种情况下都使用正确的类。
I wouldn't do either. Instead I would make it use the correct class in both cases.
public abstract class AbstractFoo {
protected final Log log = LogFactory.getLog(getClass());
...
}
public class Foo extends AbstractFoo {
public void someMethod() {
log.info("Using abstract log");
}
}
如果你没有做大量的记录(这是不管怎样,你可以使用一种方法。
If you are not doing lots of logging (which is a good idea anyway) you can use a method instead.
public abstract class AbstractFoo {
protected Log log() { return LogFactory.getLog(getClass()); }
...
}
如果有这个调用了很多的类,你可以覆盖它来给你一个缓存的实例。
If there is a class which calls this a lot you can override it to give you a cached instance.
这篇关于Java记录与抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!