...

/

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 threading
class Logger:
_instance = None
_lock = threading.Lock() # Lock for thread-safe instantiation
def __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
@staticmethod
def get_instance():
return Logger()

Code explanation

  • Line 4–5: Created the _instance variable that holds the singleton instance of the Logger class and a _lock variable containing threading.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 ...