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?
It explains the usage of a Logger Singleton class quite well. A classic example of a true singleton is a logging service. Suppose we have an event-based logging service: Client objects request that text be logged by sending a message to the logging service.
Singletons are well testable while a static class may not; If your class stores state (data), running multiple tests might effect each other, so writing test will be harder. Static classes are hard or impossible to mock. So, if you are testing a class depends on the static class, mocking may not be an easy option.
Singleton classes are used for logging, driver objects, caching and thread pool, database connections. An implementation of singleton class should have following properties:
Singleton pattern is a design pattern which restricts a class to instantiate its multiple objects. It is nothing but a way of defining a class. Class is defined in such a way that only one instance of the class is created in the complete execution of a program or project.
I found this here on the IBM site. It explains the usage of a Logger Singleton class quite well.
A classic example of a true singleton is a logging service. Suppose we have an event-based logging service: Client objects request that text be logged by sending a message to the logging service. Other objects actually log the text somewhere (console, file, whatever) by listening to the logging service for these logging requests and handling them. First, notice that the logging service passes the classic test for being a singleton:
- The requesters need a well-known object to which to send requests to log. This means a global point of access.
- Since the logging service is a single event source to which multiple listeners can register, there only needs to be one instance.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With