简体   繁体   English

Python 3.10。 TimedRotatingFileHandler 写入不同的文件

[英]Python 3.10. TimedRotatingFileHandler writes in different file

I'm trying to use the logging module in python 3.10 to create daily log files.我正在尝试使用 python 3.10 中的日志记录模块来创建每日日志文件。 Here is how I proceed:这是我的处理方式:

test.py测试.py

cwd = os.path.dirname(os.path.realpath(__file__))

# configure logger
logging.config.fileConfig(Path(cwd, "logging.ini"))
logger = logging.getLogger("test")

for i in range(10):
    logger.log(logging.INFO, "bonjour")
    time.sleep(1)

classCustomLogging.py类CustomLogging.py

class CustomTimedRotatingFileHandler(logging.handlers.
                                     TimedRotatingFileHandler):


    def __init__(self, prefix, when, backupCount):

        cwd = os.path.dirname(os.path.realpath(__file__))
        self.dir_log = Path(cwd, "Logs")

        file_path = Path(self.dir_log, f"{prefix}.log")
        log_files = Path(self.dir_log).glob("**/*.log")

        logging.handlers\
               .TimedRotatingFileHandler.__init__(self,
                                                  file_path,
                                                  when=when,
                                                  backupCount=backupCount)

and logging.ini和 logging.ini

[loggers]
keys=root, test

[handlers]
keys=customLogging_info, consoleHandler

[formatters]
keys=main

[handler_consoleHandler]
class=StreamHandler
level=CRITICAL
formatter=main
args=(sys.stdout,)

[logger_test]
level=DEBUG
handlers=customLogging_info
qualname=test

[logger_root]
handlers=consoleHandler

[handler_customLogging_info]
level=DEBUG
class=classCustomLogging.CustomTimedRotatingFileHandler
formatter=main
args = ("Debug","S", 2)

[formatter_main]
class=classCustomLogging.CustomFormatter

While testing I'm excepting to have only 2 files which are rotating every seconds but instead I'm getting:在测试时,我除了只有 2 个文件每秒钟旋转一次之外,但我得到了:

Debug.log
Debug.log.2022-02-11_17-46-08
Debug.log.2022-02-11_17-46-09

And in the Debug.log a new line is written every seconds but not appended, like if whatever happens the log will also be written in this file anyway.在 Debug.log 中,每秒钟都会写入一个新行但不会附加,就像无论发生什么日志也将写入此文件一样。 The log in the timestamped file seems correct tough.带时间戳的文件中的日志似乎很正确。 Is this a normal behavior?这是正常行为吗? Or where is the error?或者错误在哪里?

Hoping I was clear enough.希望我足够清楚。

I found a way to achieve my goal by re-implementing some of the method based on this answer我找到了一种方法来实现我的目标,方法是根据这个答案重新实现一些方法

class CustomTimedRotatingFileHandler(logging.handlers.
                                 TimedRotatingFileHandler):

def __init__(self, prefix, when, backupCount):

    """
    :param prefix: string, prefix for log file
    :param when: frequency of rotation
    :param backUpCount: int, number o file to keep
    """

    if when == "S":
        suffix = "%Y-%m-%d_%H-%M-%S"
    elif when == "M":
        suffix = "%Y-%m-%d_%H-%M"
    elif when == "H":
        suffix = "%Y-%m-%d_%H"
    elif when == "D" or when == "MIDNIGHT":
        suffix = "%Y-%m-%d"
    elif when.startswith("W"):
        suffix = "%Y-%m-%d"
    else:
        raise ValueError("Invalid rollover interval specified: %s"
                         % self.when)

    cwd = os.path.dirname(os.path.realpath(__file__))
    self.dir_log = Path(cwd, "Logs")
    self.prefix  = prefix
    self.ext = ".log"

    filename = Path(self.dir_log, f"{self.prefix}{time.strftime(suffix)}{self.ext}")
    log_files =self.dir_log.rglob("*.log")

    logging.handlers\
           .TimedRotatingFileHandler.__init__(self,
                                              filename,
                                              when=when,
                                              backupCount=backupCount)


def getFilesToDelete(self):

    """
    Re-implement base method
    """

    fileNames = os.listdir(self.dir_log)
    result = []
    plen = len(self.prefix)
    for fileName in fileNames:
        extlen = len(self.ext)
        if fileName[:plen] == self.prefix:
            suffix = fileName[plen:-extlen]
            if self.extMatch.match(suffix):
                result.append(os.path.join(self.dir_log, fileName))
    result.sort()

    if len(result) < self.backupCount:
        result = []
    else:
        result = result[:len(result) - self.backupCount]

    return result


def doRollover(self):

    """
    Re-implement base method
    """

    self.stream.close()

    # get the time that this sequence started at and make it a TimeTuple
    t = self.rolloverAt - self.interval

    self.baseFilename = Path(self.dir_log, f"{self.prefix}{time.strftime(self.suffix)}{self.ext}")

    if self.encoding:
        self.stream = codecs.open(self.baseFilename, "w", self.encoding)
    else:
        self.stream = open(self.baseFilename, "w")

    self.rolloverAt = self.rolloverAt + self.interval
    if self.backupCount > 0:
        for s in self.getFilesToDelete():
            os.remove(s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM