在Java中跨类实现Logger的标准方法? [英] Standard way to implement a Logger across classes in Java?

查看:163
本文介绍了在Java中跨类实现Logger的标准方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建具有许多类的Javafx应用程序. 我想使用所有类的Java日志记录.但是所有选项似乎都带有过多或重复的代码.这些是我能想到的:

I'm building a Javafx application with many classes. I'd like to use java logging from all the classes. But all options seem to come with excessive or repetitive code. These are the ones I can think of:

  1. 在每个类中将Logger声明为私有的static final字段,即

  1. declare Logger as a private static final field in each class i.e.

私有静态最终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.

  1. 将Logger从主类传递给每个构造函数

再次显得不太优雅

  1. 仅为记录器创建一个类,然后为每个日志项目在该类上调用静态方法. 似乎仅仅为记录器创建一个额外的类是多余的.
  1. create a class just for the logger, and then call static methods on that class for each log item. Seems like creating an additional class just for the logger is excessive.

那么你们如何处理这种情况?选择最坏的选择只是问题吗?

So how do you guys deal with this situation ? Is it just a matter of choosing the least bad option ?

推荐答案

我不同意第三个选项的过多":包装器"选项实际上非常优雅,因为它具有专用于记录器的类( SRP ),它允许您切换实施方式( apache- commons-logging java .util.logging 等),而无需将其余代码耦合到该实现.

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.

如Luiggi在下面的评论中提到的, SLF4J 就是这样的实现.

As Luiggi mentioned in the comments below SLF4J is such implementation.

这篇关于在Java中跨类实现Logger的标准方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆