...
/Solution: Create a Company's Logging System
Solution: Create a Company's Logging System
Learn how to implement the coded solution of a company logging system using the Singleton design pattern.
Designing the Singleton logger
First, design the Singleton Logger
class. This class will ensure that only one instance of the Logger
exists throughout the application.
Press + to interact
import threadingclass Logger:_instance = None_lock = threading.Lock() # Lock for thread-safe instantiationdef __new__(cls):if cls._instance is None:with cls._lock:if cls._instance is None:cls._instance = super().__new__(cls)cls._instance.log_file = open("application_log.txt", "a")return cls._instance@staticmethoddef get_instance():return Logger()
Code explanation
-
Line 4–5: Created the
_instance
variable that holds the singleton instance of theLogger
class and a_lock
variable containingthreading.Lock()
object for thread-safe instantiation. -
Line 7–13: Created the
__new__()
function that will ensure that only one instance is created using_lock
. If an instance exists, returns it; else, creates and assigns it. -
Line 15–17: Created the ...