为什么我们应该考虑“Logger”?作为单例类?
我们都知道日志,但是为什么我们应该将“Logger”类视为单例类呢?如果我们将其作为一个普通的非单例类,会发生什么?
We all know about log, ok, but why should we consider the «Logger» class a singleton one? What happens if we make it as a normal non-singleton class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我在 IBM 网站上找到了这个。它很好地解释了 Logger Singleton 类的用法。
这里是链接:明智地使用你的单例
如果你不这样做使用单例类,您必须处理这些不同记录器实例之间的同步(写入文件或您使用的任何流)。因此,当您只有一个全局 Logger 实例时,这就容易多了。
I found this here on the IBM site. It explains the usage of a Logger Singleton class quite well.
Here the link: Use your singletons wisely
If you wouldn't use a singleton class you would have to deal with the synchronisation (writing to a file, or whatever stream you use) between these different logger instances. So its much easier, when you just have one global Logger instance.
主要问题是实际日志的保存位置。
如果您正在文件系统上进行写入,则拥有多个实例(因此可能有多个线程)可能会导致文件出现乱码。
从某种意义上说,根据缓冲和其他低级机制,来自一次写入的消息最终可能会与来自其他写入的消息(或部分消息)混合。
这可能是一个小问题,但这是我能想到的关于只有一个(因此是串行的)日志写入对象的唯一问题。
The main problem is where the actual log is persisted.
If you are writing on a filesystem, having more than one instance (and therefore, probably, more than one thread) may result in a garbled file.
In the sense that depending on buffering and other low-level mechanisms messages from one write may end up mixed with messages (or parts of messages) from others.
This may be a minor problem, but it's the only one I can think of regarding having just one (and therefore serial) log writing object.
如果您有多个具有不同内容的日志流,则可以使用为不同输出初始化的记录器类的多个实例。
但是,如果您只有一个日志流,则拥有多个记录器类实例会导致更复杂的实现,因为这些实例必须一起工作来管理实际资源。例如,考虑一个使用序列号记录每条消息的记录器。两个实例必须同步它们的序列计数器,这要求它们相互了解、协商计数器增加等等。 (在静态类成员中使用共享计数器的替代方法相当于使用单例记录器)
If you have more than one log streams with different content, you can use multiple instances of the logger class initialized for the different outputs.
However, if you have only one log stream, having multiple logger class instances leads to more complex implementation, as the instances have to work together to manage the actual resource. Consider for example a logger that logs each message with a sequence number. Two instances will have to synchronize their sequence counters, which requires them to knwp about each other, negotiate counter increases and so on. (The alternative of having shared counter in a static class member is equivalent to having a singleton logger)
我相信我们也可以用完文件描述符
I believe we can also run out of file descriptors
取决于日志记录框架。通常您希望所有消息都转到一个日志,因此您希望所有代码都使用同一个记录器。但记录器类不必是单例才能确保这一点。
Depends on the logging framework. Usually you want all messages to go to one log, so you want all code to use the same logger. But the logger-class does not have to be a singleton to ensure that.