How can I add some basic details in starting of each log file in python

Viewed 32

I want to add created date, created user details(some basic details) in starting of each log file in python

 def errorlog(cls, filename, level=logging.DEBUG):
        file_handler = RotatingFileHandler(
            os.path.join(BASE_DIR, name, filename),
            maxBytes=100,
            mode= write_mode,
            backupCount=10,
        )
        file_handler.setFormatter(formatter)
        if (logger.hasHandlers()):
            logger.handlers.clear()
        logger.addHandler(file_handler)

here I am getting the new log files but what I want is when a log file is created, I want to add some basic details as default like

#--------------------------#
# Created by  : xxx
# Employee ID : xxx
# Date        : xxxx
#--------------------------#

how can I do this

1 Answers

There might be some less hacky solution, but I came up with the following (it is implemented for logging.FileHandler but should work just as well if you inherit from RotatingFileHandler:

from datetime import date
import os

class HeaderFileHandler(logging.FileHandler):
    def _open(self):
        open_func = self._builtin_open
        new_log = not os.path.exists(self.baseFilename)
        f = open_func(self.baseFilename, self.mode,
                         encoding=self.encoding, errors=self.errors)
        if new_log:
            f.write(f"Log created on {date.today()}\n")
        return f

Then change your handler class to this custom one.

Related