8

I want to change the way that the rotating file handler names files.

For example, if I use RotatingFileHandler, it separates the log file when it reaches a specific file size naming "log file name + extension numbering", like below.

filename.log      #first log file
filename.log.1    #rotating log file1
filename.log.2    #rotating log file2

However, I want the log handler to name them every time it is created. For example.

09-01-12-20.log    #first log file
09-01-12-43.log    #rotating log file1
09-01-15-00.log    #rotating log file2

How can I do this?

Edit:

I am not asking how to create and name a file.

I want to facilitate python logging package doing something like inheriting and overriding logging.

2 Answers 2

14

I inherit and override RotatingFileHandler of python logging handler.

RotatingFileHandler has self.baseFilename value, the handler will use self.baseFilename to create logFile.(when it creates file first or when rollover happens)

self.shouldRollover() method, It checks if the handler should rollover logfile or not.

If this method return 1, it means rollover should happen or return 0.

By overriding them, I define when this handler makes rollover and which name should be used for new log file by rollover.

-----------------------------------------Edit-----------------------------------------

I post the example code.

from logging import handlers

class DailyRotatingFileHandler(handlers.RotatingFileHandler):

    def __init__(self, alias, basedir, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
        """
        @summary: 
        Set self.baseFilename to date string of today.
        The handler create logFile named self.baseFilename
        """
        self.basedir_ = basedir
        self.alias_ = alias

        self.baseFilename = self.getBaseFilename()

        handlers.RotatingFileHandler.__init__(self, self.baseFilename, mode, maxBytes, backupCount, encoding, delay)

    def getBaseFilename(self):
        """
        @summary: Return logFile name string formatted to "today.log.alias"
        """
        self.today_ = datetime.date.today()
        basename_ = self.today_.strftime("%Y-%m-%d") + ".log" + '.' + self.alias_
        return os.path.join(self.basedir_, basename_)

    def shouldRollover(self, record):
        """
        @summary: 
        Rollover happen 
        1. When the logFile size is get over maxBytes.
        2. When date is changed.

        @see: BaseRotatingHandler.emit
        """

        if self.stream is None:                
            self.stream = self._open()

        if self.maxBytes > 0 :                  
            msg = "%s\n" % self.format(record)
            self.stream.seek(0, 2)  
            if self.stream.tell() + len(msg) >= self.maxBytes:
                return 1

        if self.today_ != datetime.date.today():
            self.baseFilename = self.getBaseFilename()
            return 1

        return 0

This DailyRotatingFileHandler will create logfile like

2016-10-05.log.alias
2016-10-05.log.alias.1
2016-10-05.log.alias.2
2016-10-06.log.alias
2016-10-06.log.alias.1
2016-10-07.log.alias.1
Sign up to request clarification or add additional context in comments.

1 Comment

@FredFury I add an example code, It hopes it could help you.
-2

Check the following code and see if it helps. As far as I could understand from your question if your issue is in achieving the filename based on timestamp then this shall work for you.

import datetime, time
# This return the epoch timestamp    
epochTime = time.time()
# We generate the timestamp 
# as per the need
timeStamp = datetime.datetime\
                    .fromtimestamp(epochTime)\
                    .strftime('%Y-%m-%d-%H-%M')
# Create a log file 
# use timeStamp as filename
fo = open(timeStamp+".log", "wb")
fo.write("Log data")
fo.close()

1 Comment

I already know how to handle time and create file but What I want is with Python logging facilating Python logging functions. it can be something like inheriting logging class and overriding logging method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.