0

I need to create my log files such that the roll over should happen if the size exceeds 10KB or new file for every 2 mins. (For testing purpose)

So, I am trying to implement this logic in my code.

My main code looks like this:

from ImsLogging import EnhancedRotatingFileHandler
import logging

logs_path = os.path.join(os.getcwd(),"Logs")
Path(logs_path).mkdir(parents=True, exist_ok=True)
filename = datetime.now().strftime('Notebook_%H%M%d%m%Y.log')
log_fname = os.path.join(logs_path, filename)
logging.setLoggerClass(EnhancedRotatingFileHandler)
logging.basicConfig(filename=log_fname,
format='{"@timestamp":"%(asctime)s","log.level":"%(levelname)-1s","message":"%(message)s"}',
datefmt='%m/%d/%Y %H:%M:%S %p')
logger = logging.getLogger("Notebook_")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setLevel(logging.ERROR)
logger.addHandler(handler)

logger.info("Notebook Process Started !!!")

My customized logger code is :

class EnhancedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler,logging.Logger):
    def __init__(self, filename, when='M', interval=2, backupCount=10, encoding=None, delay=0, utc=0, maxBytes=10240):
        """ This is just a combination of TimedRotatingFileHandler and RotatingFileHandler (adds maxBytes to TimedRotatingFileHandler)  """
        logging.handlers.TimedRotatingFileHandler.__init__(self, filename, when, interval, backupCount, encoding, delay, utc)
        print (filename)
        logging.Logger.__init__(self)
        self.maxBytes=maxBytes

    def shouldRollover(self, record):
        """
        Determine if rollover should occur.

        Basically, see if the supplied record would cause the file to exceed
        the size limit we have.

        we are also comparing times        
        """
        if self.stream is None:                 # delay was set...
            self.stream = self._open()
        if self.maxBytes > 0:                   # are we rolling over?
            msg = "%s\n" % self.format(record)
            self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
            if self.stream.tell() + len(msg) >= self.maxBytes:
                return 1
        t = int(time.time())
        if t >= self.rolloverAt:
            return 1
        print ("No need to rollover: %d, %d" % (t, self.rolloverAt))
        return 0         

The logger file is getting created but the Rollover is not happening irrespective of the size / interval.

Can any help what I am missing here.

Thanks.

usr_lal123
  • 650
  • 12
  • 28

0 Answers0