I am trying to create a class that can create multiple instances of logging with saved .log.
This is my code:
import logging
from datetime import datetime
import sys
import os
class DummyLog:
def __init__(self,
log_name: str = datetime.now().strftime('%d_%m_%Y__%H_%M_%S'),
logging_level: str = 'debug',
string_format: str = '%(asctime)s: %(levelname)s: %(message)s',
datetime_format: str = '%m/%d/%Y %I:%M:%S %p',
log_on_folder: bool = True,
log_folder_name: str = 'logs'
):
self.logName = log_name
self.logger = None
self.loggingLevel = logging_level
self.stringFormat = string_format
self.datetimeFormat = datetime_format
if log_on_folder:
if not os.path.exists(log_folder_name):
os.mkdir(log_folder_name)
self.logName = log_folder_name + '/' + self.logName
self.initiateLogger()
def initiateLogger(self):
""" This function will initiate the logger as a single threaded log"""
self.logger = logging.getLogger(self.logName)
if self.loggingLevel == 'debug':
self.loggingLevel = logging.DEBUG
self.logger.setLevel(self.loggingLevel)
logFormat = logging.Formatter(self.stringFormat, datefmt=self.datetimeFormat)
# Creating and adding the console handler
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormat)
self.logger.addHandler(consoleHandler)
# Creating and adding the file handler
fileHandler = logging.FileHandler(self.logName + ".log", mode='w')
fileHandler.setFormatter(logFormat)
self.logger.addHandler(fileHandler)
dl = DummyLog()
dl.logger.info("hi")
import time
time.sleep(1)
dl1 = DummyLog()
dl1.logger.info("hi")
When I run the above code, it creates only one .log file and both the dl and dl1 objects are being logged on the same .log file.
The console output is printing the log 3 times instead of 2 times:
01/03/2022 12:01:20 PM: INFO: hi
01/03/2022 12:01:21 PM: INFO: hi
01/03/2022 12:01:21 PM: INFO: hi
but I have initiated the class Dummylog two times. I am expecting the code change where the class DummyLog can be called at multiple instances and each instance will save an individual .log file.
I know I am missing something in the Handler, but nothing is helping me to come over the required change.
Any help will be appreciated !!