python 按时间 and 文件大小分割日志

目的

logging.handlers模块自带的文件分割只支持一下两种模式:

RotatingFileHandler 类位于 logging.handlers 模块,它支持磁盘日志文件的轮换。
TimedRotatingFileHandler 类位于 logging.handlers 模块,它支持基于特定时间间隔的磁盘日志文件轮换。
详见python官方文档

有些时候我们需要按时间分割,但是如果日志过多,还是存在文件过大的情况,这个时候就需要在时间的维度上再根据文件大小进行分割,所以就有了按时间+文件大小的维度分割文件的想法。
具体如下:

代码

#test5.py
from logging.handlers import TimedRotatingFileHandler

import os
import time

_MIDNIGHT = 24 * 60 * 60


class TimedSizeRotatingFileHandler(TimedRotatingFileHandler):
    """
    拓展TimedRotatingFileHandler,按时间和文件大小分割
    """

    def __init__(self, filename, maxBytes=0, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None):
        TimedRotatingFileHandler.__init__(
            self, filename, when, interval, backupCount, encoding, delay, utc, atTime)
        self.maxBytes = maxBytes
        self.count = 0

    def shouldRollover(self, record):

        t = int(time.time())
        if t >= self.rolloverAt:
            return 1

        # 文件够大时roll,搬运自RotatingFileHandler
        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

        return 0

    def doRollover(self):
        """
        do a rollover; in this case, a date/time stamp is appended to the filename
        when the rollover happens.  However, you want the file to be named for the
        start of the interval, not the current time.  If there is a backup count,
        then we have to get a list of matching filenames, sort them and remove
        the one with the oldest suffix
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kerlly_bigbig_bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值