Python记录RotatingFileHandler:旋转后文件大小仍然增加

时间:2018-07-25 09:49:24

标签: python python-2.7 logging

在python2.7中使用python日志记录模块进行文件旋转时,遇到一个问题,即旋转后直到删除原始文件的大小仍然会增加。

例如,原始文件为“ test_file”,然后大小最大为1M,并通过记录进行旋转。它将重命名为“ test_file.1”,并且大小仍会增加,日志记录模块会继续将日志写入“ test_file.1”。并且直到它变成“ test_file.2”并且“ test_file”最大为1M。 “ test_file.2”将被删除,其他所有功能都将按预期运行。

下面是代码:

#!/usr/bin/python
# coding=utf-8
import os, stat
import logging
from logging.handlers import RotatingFileHandler

class GroupWriteRotatingFileHandler(RotatingFileHandler):

    def doRollover(self):
        """
        Override base class method to make the new log file group writable.
        """
        # Rotate the file first.
        RotatingFileHandler.doRollover(self)

        # Add group write to the current permissions.
        currMode = os.stat(self.baseFilename).st_mode
        os.chmod(self.baseFilename, currMode | stat.S_IWGRP | stat.S_IWOTH | stat.S_IWUSR)

logging.basicConfig(level=logging.INFO,
                format='%(asctime)s [%(levelname)s] %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='/opt/cc/cc.log',
                filemode='a')

# print log which level is higher than 'INFO' to screen.
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
# formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

# 3 log backup , each size is 5M 
# Rthandler = RotatingFileHandler('file_name', maxBytes=5*1024*1024, backupCount=5)
Rthandler = GroupWriteRotatingFileHandler('file_name', maxBytes=1*1024*1024, backupCount=2)
Rthandler.setLevel(logging.INFO)
# formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)

0 个答案:

没有答案