【问题标题】:Can I delay the rotation of the logfile when using the Twisted logger?使用 Twisted 记录器时可以延迟日志文件的轮换吗?
【发布时间】:2020-05-24 10:41:47
【问题描述】:

当使用logging 模块创建轮换日志文件时,我可以使用TimedRotatingFileHandler 类的delay=True 参数告诉记录器延迟轮换直到有实际数据要记录,如下所示:

import time
import logging
from logging.handlers import TimedRotatingFileHandler

if __name__ == '__main__':
    handler = TimedRotatingFileHandler('logfile.log', when='midnight', delay=True)
    out_fmt = '[%(asctime)s.%(msecs)03dZ] [%(levelname)s] %(message)s'
    dt_fmt = '%Y-%m-%d %H:%M:%S'
    logging.Formatter.converter = time.gmtime
    formatter = logging.Formatter(out_fmt, dt_fmt)
    handler.setFormatter(formatter)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(handler)

当很少有新信息输出到日志时,这很有用 - 例如,如果有一整天没有任何新信息被记录;那么你不想为那一天创建一个空的日志文件。

使用 Twisted logger (twisted.python.logfile.DailyLogFile) 是否可以达到同样的效果?

【问题讨论】:

    标签: python logging twisted


    【解决方案1】:

    您可以实现您想要的行为,只需覆盖DailyLogFile 类中的shouldRotate 函数。

    类似下面的东西应该可以解决问题:

    class CustomDailyLogFile(LogFile, DailyLogFile):
        def shouldRotate(self):
            return self.toDate() > self.lastDate and self.rotateLength and self.size >= self.rotateLength
    

    【讨论】:

    • 我理解这个想法并且我喜欢它,但我似乎无法像这样访问rotateLengthsize。这些变量是 LogFile 类的本地变量 - 而不是 DailyLogFile 类。
    • 哦,我没有意识到这一点。您也可以添加其他类。我将编辑答案。
    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多