在Python

时间:2016-09-02 14:00:50

标签: python logging

我想根据需要命名旋转日志文件。

例如,如果我使用RotatingFileHandler,它会在日志文件达到命名log file name + extension numbering的特定文件大小时将其分开,如下所示。

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

但是,我希望日志处理程序在每次创建时都为它们命名。 例如。

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

我该怎么做?

编辑---------------------------

我不是在问如何创建和命名文件。

我希望让python logging包进行继承和覆盖logging之类的操作。

2 个答案:

答案 0 :(得分:2)

我继承并覆盖了python日志处理程序的RotatingFileHandler

RotatingFileHandler的值为self.baseFilename,处理程序将使用self.baseFilename创建logFile。(当它首先创建文件或发生翻转时)

self.shouldRollover()方法,它检查处理程序是否应该翻转日志文件。

如果使用此方法return 1,则表示应该进行翻转或return 0

通过覆盖它们,我定义此处理程序何时进行翻转以及应该通过翻转将哪个名称用于新日志文件。

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

我发布了示例代码。

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

这个DailyRotatingFileHandler将创建类似

的日志文件
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

答案 1 :(得分:1)

检查以下代码,看看是否有帮助。据我所知,如果你的问题是根据时间戳获得文件名,那么这对你有用。

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()