免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 8264 | 回复: 0
打印 上一主题 下一主题

使用TimedRotatingFileHandler自定义日志后缀的问题 [复制链接]

论坛徽章:
1
数据库技术版块每日发帖之星
日期:2016-01-01 06:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-06-26 11:24 |只看该作者 |倒序浏览
  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

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP