[英]Standard way to implement a Logger across classes in Java?
I'm building a Javafx application with many classes. 我正在构建一个包含许多类的Javafx应用程序。 I'd like to use java logging from all the classes.
我想从所有类中使用java日志记录。 But all options seem to come with excessive or repetitive code.
但是所有选项似乎都带有过多或重复的代码。 These are the ones I can think of:
这些是我能想到的:
declare Logger as a private static final field in each class ie 将Logger声明为每个类中的私有静态final字段,即
private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName()); private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());
This option seems kind of annoying having to do this in each class. 这个选项似乎有点烦人,必须在每个班级都这样做。
Again does not seem elegant 再次似乎并不优雅
So how do you guys deal with this situation ? 那你们怎么处理这种情况呢? Is it just a matter of choosing the least bad option ?
这只是选择最不好选择的问题吗?
Option 1 coupled with option 3 (like folks mentioned using a wrapper like slf4j) which will allow switching between implementations is widely used. 选项1与选项3相结合(就像人们提到的使用类似slf4j的包装器)将允许在实现之间进行切换被广泛使用。
declare Logger as a private static final field in each class i.e.
private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());
Declaring a logger isn't such a big deal and you should be able to define a new class template in your IDE which auto generates the logger code. 声明一个记录器并不是什么大问题,你应该能够在IDE中定义一个新的类模板,它自动生成记录器代码。
I disagree about the "excessiveness" of the third option: the "wrapper" option is actually quite elegant because it has a dedicated class for logger ( SRP ) and it allows you to switch implementations ( log4j , apache-commons-logging , java.util.logging etc) "under the hood" without coupling the rest of the code to that implementation. 我不同意第三种选择的“过度”:“包装”选项实际上相当优雅,因为它有一个专用的记录器类( SRP ),它允许你切换实现( log4j , apache-commons-logging , java。 util.logging etc)“引擎盖下”没有将其余代码耦合到该实现。
As Luiggi mentioned in the comments below SLF4J is such implementation. 正如Luiggi在下面的评论中提到的那样, SLF4J就是这样的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.