- 论坛徽章:
- 1
|
- import logging,logging.handlers,time,datetime
- myLogger = logging.getLogger()
- rthandler = logging.handlers.TimedRotatingFileHandler("test", 'S', 5, 5)
- #rthandler.extMatch = r"^\d{4}-\d{2}-\d{2}__\d{2}\d{2}\d{2}$"
- rthandler.suffix = "%Y-%m-%d__%H%M%S"
- myLogger.addHandler(rthandler)
- while True:
- myLogger.error(datetime.datetime.now())
- time.sleep(1)
复制代码 如上面代码所示,我使用TimedRotatingFileHandler设置日志每5秒生成一个新文件,后缀是%Y-%m-%d__%H%M%S,只保留5个最近的文件。
但这样实际运行后,并不能删除旧的日志文件,好像是因为修改了.suffix以后,后缀不再与默认的extMatch内容匹配导致的。
但我如果把上面的注释行去掉,自己指定.extMatch属性,又会报错:
Traceback (most recent call last):
File "C:\Python27\lib\logging\handlers.py", line 77, in emit
self.doRollover()
File "C:\Python27\lib\logging\handlers.py", line 352, in doRollover
for s in self.getFilesToDelete():
File "C:\Python27\lib\logging\handlers.py", line 310, in getFilesToDelete
if self.extMatch.match(suffix):
AttributeError: 'str' object has no attribute 'match'
Logged from file HelloWorld.py, line 8
请问大家是怎么实现既能让文件以指定后缀保存,又能删除旧的文件的呢?我用的python版本是2.7
|
|