如何在代码中使用log4j?
我们必须在我们的应用程序中引入日志记录。我们决定使用log4j,它是一个不错的选择。还有人告诉我们应该使用单例模式来使用 log4j 有人可以强调如何以及为什么吗?
We have to introduce logging in our application. We have decided to use log4j is it a good choice. Also somebody told that we should use singleton pattern for using log4j can somebody emphasise how and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在单例模式中,
Logger
字段对于类来说是静态的:另一种方法是使
Logger
字段成为非静态的(即,SomeAwesomeClass 的每个实例
包含对Logger
的引用):我认为您选择的路由没有太大区别,因为我相信 Log4j 会不断返回相同的
Logger
SomeAwesomeClass
的每个实例的实例。实际上,这只是不必要的对象引用,所以您不妨使用单例模式。但是,如果您执行以下操作,则非单例模式就变得必要:
稍后...
在此示例中,
logger
字段将对应于AwesomerClass,而不是
SomeAwesomeClass
。In the singleton pattern, the
Logger
field is static to the class:The alternative is to make the
Logger
field non-static (that is, each instance ofSomeAwesomeClass
holds a reference to theLogger
):I don't think it makes a lot of difference which route you choose as I believe Log4j will continually return the same
Logger
instance for each instance ofSomeAwesomeClass
. Really, it's just unnecessary object references, so you might as well use the singleton pattern.However, the non-singleton pattern becomes necessary if you do something like this:
Later...
In this example, the
logger
field will correspond toAwesomerClass
, notSomeAwesomeClass
.如果您是第一次引入日志记录,请使用 Logback。按照此处建议使用配置文件,并将其添加到类路径中。日志记录将自动配置。
If you are introducing logging for the first time then use Logback. Use the configuration file as suggested here and add it to the classpath. Logging will be auto configured.
Singleton 有时更可取的原因是我们每个应用程序只需要一个 Logger 实例,否则,对于每个新的 logger 实例,都会有一个新创建的文件或覆盖现有的文件日志档案。
至于 Log4J 是否是一个好的选择将取决于您对不同可用记录器的研究/经验。这完全取决于您的偏好(我一直使用 Log4J,因为我发现它更容易配置,但我对任何记录器都没有偏见)。
著名的有:
网络上有一些示例向您展示如何使用记录器。 这里是 Log4J 与 SLF4J 的简要比较。
The reason why Singleton is sometimes preferable is that we want only one instance of the Logger per application, otherwise, for every new instance of the logger, there will be a newly created file or an overwrite of an existing log file.
As to whether Log4J is a good choice or not will depend on your research/experience with the different loggers available. It's all about your preference (I use Log4J all the time as I find it easier to configure, but I'm not biased to any loggers out there).
Famous ones out there are:
There are some examples on the web that shows you how to use loggers. Here is a brief comparison for Log4J vs SLF4J.