python修改logging模块实现日志按天写入

  最近使用python开发自动化测试后台,日志模块利用配置文件建立,如下:

#log4py.properties
###############################################
[loggers]
keys=root
[logger_root]
level=DEBUG
handlers=hand01,hand02
###############################################
[handlers]
keys=hand01,hand02
[handler_hand01]
class=StreamHandler
level=DEBUG
formatter=form02
args=(sys.stdout,)
[handler_hand02]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=form01
args=('../log/auto_test.log', 'D',1,0)
###############################################
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S
[formatter_form02]
#format=%(name)-12s: %(levelname)-8s %(message)s
#format=%(message)s
datefmt=

使用今天后发现并没有像想象中的那样每天新建一个log文件,并把以前的文件按天进行重命名,查看了logging模块源码(Python-2.7.8/Lib/logging/handlers.py)后发现问题所在,代码如下:

    def shouldRollover(self, record):
        """
        Determine if rollover should occur.

        record is not used, as we are just comparing times, but it is needed so
        the method signatures are the same
        """
        t = int(time.time())
        if t >= self.rolloverAt:
            return 1
        #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
        return 0

其中self.rolloverAt是log文件最后一次修改的时间+配置文件设置的时间间隔interval(如上则是60 * 60 * 24),那么根据程序判断配置的时间间隔应该就是离上次修改的时间,只有在这时才会重命名旧的日志文件并新建新的日志文件,既不是按照日志文件创建时间(猜测是由于unix不记录文件创建时间),也不是按照每天或者每周等方式重命名旧的日志文件并新建新的日志文件,因此通过修改上面的源代码就可以实现按照每天或者每分钟等方式重命名旧的日志文件并新建新的日志文件,代码如下:

    def shouldRollover(self, record):
        """
        Determine if rollover should occur.

        record is not used, as we are just comparing times, but it is needed so
        the method signatures are the same
        """
        t = int(time.time())
        #此处只实现按分钟和按天重建,其他方式可据此修改
        if self.when.startswith('M') and time.localtime(t).tm_min==time.localtime(self.rolloverAt).tm_min:
            return 1
        if self.when.startswith('D') and time.localtime(t).tm_mday==time.localtime(self.rolloverAt).tm_mday:
            return 1
        if t >= self.rolloverAt:
            return 1
        #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
        return 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值