最近使用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