Search⌘ K

Solution: Create a Company's Logging System

Explore how to create a Singleton Logger class in Python that ensures only one instance exists while supporting thread-safe logging. Understand how to implement logging methods for info, warning, and error messages in multiple modules, and manage concurrency with locks and threads to maintain reliable and consistent logs within your application.

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.

Python 3.10.4
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 ...