I have tried to use RotatingFileHandler for logging in python which is configured with maxBytes = 1000 bytes and backupCount = 5. How can i add a brief description with the file created timestamp at the beginning of each log file using the following code.
from datetime import datetime
import logging
import os
from logging.handlers import RotatingFileHandler
from general_configurations import BASE_DIR, NO_OF_LOG_FILES, FILE_SIZE, WRITE_MODE, FOLDER_NAME #These values imported from another file named general_configurations.py
class Datalogs(object):
__instance = None
@staticmethod
def get_instance():
if Datalogs.__instance is None:
Datalogs()
return Datalogs.__instance
def __init__(self):
if Datalogs.__instance is not None:
raise Exception("This class is a singleton!")
else:
Datalogs.__instance = self
@classmethod
def errorlog(cls, filename, level=logging.DEBUG):
logger = logging.getLogger()
logger.setLevel(level)
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s - %(message)s"
)
file_handler = RotatingFileHandler(
os.path.join(BASE_DIR, FOLDER_NAME , filename),
maxBytes=FILE_SIZE,
mode= WRITE_MODE,
backupCount=NO_OF_LOG_FILES,
)
file_handler.setFormatter(formatter)
if logger.hasHandlers():
logger.handlers.clear()
logger.addHandler(file_handler)
return logger
def logging_error(self, data, filename, loglevel, deviceid):
logging_error = self.errorlog(filename)
if loglevel == logging.DEBUG:
logging_error.debug(data)
elif loglevel == logging.INFO:
logging_error.info(data)
elif loglevel == logging.WARNING:
logging_error.exception(data)
elif loglevel == logging.ERROR:
logging_error.exception(data)
else:
logging_error.critical(data)
Datalogs().logging_error("helloo world","Example.log",10,101)