I want to write a Python class which uses Python logging. This Python class will be responsible for the creating a file with a given name in init function.
I want to create a object of the above class in two or more classes and expect two or files getting generated.
I tried writing this class but I am not able to create multiple files.
Can anyone guide me how do I do that?
I have created the following class:
class Logger:
def __init__(self, log_filename = "test.log"):
if not os.path.exists("LogFiles"):
os.makedirs("LogFiles")
self.Logger = logging.getLogger("main")
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s : %(message)s',
filename= log_filename,
filemode='w') # change filemode to 'w' to overwrite file on each run
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(message)s')
consoleHandler.setFormatter(formatter)
logging.getLogger('').addHandler(consoleHandler) # Add to the root logger
self.Logger.info("Starting new logging sessions")
def writeToFile(self, line):
if self.Logger.propagate == True:
self.Logger.debug(line)
def closeFile(self):
if self.Logger.propagate == True:
self.Logger.propagate = False