Write a header at every logfile that is created with a time-rotating logger
I've solved it! Basically all that needs to be done is overriding the doRollover
method of the TimedRotatingFileHandler
, also some code is needed in this new parent class in order to pass the logging instance and set the header content. Hereby an extensive example for people who encounter a similar situation.
from logging.handlers import TimedRotatingFileHandler
class MyTimedRotatingFileHandler(TimedRotatingFileHandler):
def __init__(self, logfile, when, interval):
super(MyTimedRotatingFileHandler, self).__init__(logfile, when, interval)
self._header = ""
self._log = None
def doRollover(self):
super(MyTimedRotatingFileHandler, self).doRollover()
if self._log is not None and self._header != "":
self._log.info(self._header)
def setHeader(self, header):
self._header = header
def configureHeaderWriter(self, header, log):
self._header = header
self._log = log
# create time-rotating log handler
logHandler = MyTimedRotatingFileHandler(logfile, when='midnight')
form = '%(asctime)s %(name)s %(levelname)s: %(message)s'
logFormatter = logging.Formatter(form)
logHandler.setFormatter(logFormatter)
# create logger
log = logging.getLogger('MyLogger')
logHandler.configureHeaderWriter('test-header', log)
log.addHandler(logHandler)
log.setLevel(logging.INFO)