Chinaunix

标题: 使用TimedRotatingFileHandler自定义日志后缀的问题 [打印本页]

作者: number321    时间: 2015-06-26 11:24
标题: 使用TimedRotatingFileHandler自定义日志后缀的问题
  1. import logging,logging.handlers,time,datetime
  2. myLogger = logging.getLogger()
  3. rthandler = logging.handlers.TimedRotatingFileHandler("test", 'S', 5, 5)
  4. #rthandler.extMatch = r"^\d{4}-\d{2}-\d{2}__\d{2}\d{2}\d{2}$"
  5. rthandler.suffix = "%Y-%m-%d__%H%M%S"
  6. myLogger.addHandler(rthandler)
  7. while True:
  8.     myLogger.error(datetime.datetime.now())
  9.     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


作者: dhuib    时间: 2017-04-14 10:44
rthandler.extMatch = re.compile( r"^\d{4}-\d{2}-\d{2}__\d{2}\d{2}\d{2}$")




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2