I am doing this project on Python 2.7 and I am trying to convert this function that returns a logging object. I am trying to make sure that I can utilize the same object instance through different python modules by importing it without actually creating new instances? For e.g if I actually import the module where the instance was created originally, each time I import it a new instance gets created. But I want to use the same original instance, throughout all different modules, that was created the first time I ran that module since multiple lines are being printed out inside my log file due to multiple instances. That is why a singleton class in Python 2.7 is required but I am not sure how to convert this function into a singleton class such that it returns one instance and I can use it throughout all my different modules by importing without triggering new instances. The setLogger function creates a logger instance which inputs logs into the file_name log file.
def setLogger(file_name):
logger = logging.getLogger(__name__)
if not getattr(logger, 'handler_set', None):
logger.setLevel(logging.INFO)
stream_handler = logging.StreamHandler()
file_handler = logging.FileHandler(file_name)
formatter = logging.Formatter('%(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
logger.setLevel(logging.INFO)
logger.propagate = False
logger.handler_set = True
return logger