栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python,想要通过日志轮换和压缩进行日志记录

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python,想要通过日志轮换和压缩进行日志记录

  • 每天进行日志轮换: 使用TimedRotatingFileHandler
  • 日志压缩 :设置
    encoding='bz2'
    参数。(请注意,此“技巧”仅适用于Python2。’bz2’不再被视为Python3中的编码。)
  • 可选-删除最早的日志文件以保留X MB的可用空间 。您可以(间接)使用RotatingFileHandler安排它。通过设置该
    maxBytes
    参数,日志文件将在达到一定大小时翻转。通过设置
    backupCount
    参数,您可以控制保留多少翻转。这两个参数一起使您可以控制日志文件占用的最大空间。您可能可以将其子类化,
    TimeRotatingFileHandler
    以将这种行为也纳入其中。

只是为了好玩,这是您可以如何子类化

TimeRotatingFileHandler
。当您运行以下脚本时,它将把日志文件写入
/tmp/log_rotate*

使用较小的

time.sleep
(例如0.1)值,日志文件会迅速填满,达到maxBytes限制,然后再进行滚动。

较大

time.sleep
(例如1.0)时,日志文件会缓慢填充,不会达到maxBytes限制,但是无论何时(达到10秒的时间间隔),它们都会翻转。

以下所有代码均来自logging /
handlers.py
。我只是以最简单的方式将TimeRotatingFileHandler与RotatingFileHandler网格化。

import timeimport reimport osimport statimport loggingimport logging.handlers as handlersclass SizedTimedRotatingFileHandler(handlers.TimedRotatingFileHandler):    """    Handler for logging to a set of files, which switches from one file    to the next when the current file reaches a certain size, or at certain    timed intervals    """    def __init__(self, filename, maxBytes=0, backupCount=0, encoding=None,      delay=0, when='h', interval=1, utc=False):        handlers.TimedRotatingFileHandler.__init__( self, filename, when, interval, backupCount, encoding, delay, utc)        self.maxBytes = maxBytes    def shouldRollover(self, record):        """        Determine if rollover should occur.        Basically, see if the supplied record would cause the file to exceed        the size limit we have.        """        if self.stream is None:      # delay was set... self.stream = self._open()        if self.maxBytes > 0:        # are we rolling over? msg = "%sn" % self.format(record) # due to non-posix-compliant Windows feature self.stream.seek(0, 2) if self.stream.tell() + len(msg) >= self.maxBytes:     return 1        t = int(time.time())        if t >= self.rolloverAt: return 1        return 0def demo_SizedTimedRotatingFileHandler():    log_filename = '/tmp/log_rotate'    logger = logging.getLogger('MyLogger')    logger.setLevel(logging.DEBUG)    handler = SizedTimedRotatingFileHandler(        log_filename, maxBytes=100, backupCount=5,        when='s', interval=10,        # encoding='bz2',  # uncomment for bz2 compression    )    logger.addHandler(handler)    for i in range(10000):        time.sleep(0.1)        logger.debug('i=%d' % i)demo_SizedTimedRotatingFileHandler()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610468.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号