python的logging库中TimedRotatingFileHandler类问题

2023-11-20 22:38

本文主要是介绍python的logging库中TimedRotatingFileHandler类问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原文网址:http://www.5dcode.com/?p=545

第一次用python,第一次用logging,第一次用TimedRotatingFileHandler,居然发现了其中的BUG,记录下吧。

      用TimedRotatingFileHandler的目的是让其自动在日志文件名后面加上日期时间,可以按秒、分、时、天、周或者其倍数来设置,BUG出现的场景是:手动设置时间,并把时间往未来时间调(比如把2012-03-15调成2014-03-15),这时就出问题了,这时产生每条日志后会产生一个日志文件,这并不是我们想要的效果,如果把当前时间再往历史时间调(比如把2012-03-15调成2010-03-15),这时也会产生问题:所有产生的日志都会记录到一个没有日期后缀的文件,并不会按日期分类。如果时间是正确的并按正常的流程走并不会产生问题,所以想看看logging是怎么实现的,看了其源码:C:\Python25\Lib\logging\handlers.py,果然不出所料,它的设计是有问题的,根本不考虑手动调时间或者时间可能不对需要同步的情况:

  1. def shouldRollover(self, record):
  2.         """
  3.         Determine if rollover should occur
  4.  
  5.         record is not used, as we are just comparing times, but it is needed so
  6.         the method siguratures are the same
  7.         """
  8.         t = int(time.time())
  9.         if t >= self.rolloverAt:
  10.             return 1
  11.         #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
  12.         return 0
  13.  
  14.     def doRollover(self):
  15.         """
  16.         do a rollover; in this case, a date/time stamp is appended to the filename
  17.         when the rollover happens.  However, you want the file to be named for the
  18.         start of the interval, not the current time.  If there is a backup count,
  19.         then we have to get a list of matching filenames, sort them and remove
  20.         the one with the oldest suffix.
  21.         """
  22.         self.stream.close()
  23.         # get the time that this sequence started at and make it a TimeTuple
  24.         t = self.rolloverAt - self.interval
  25.         timeTuple = time.localtime(t)
  26.         dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
  27.         if os.path.exists(dfn):
  28.             os.remove(dfn)
  29.         os.rename(self.baseFilename, dfn)
  30.         if self.backupCount > 0:
  31.             # find the oldest log file and delete it
  32.             s = glob.glob(self.baseFilename + ".20*")
  33.             if len(s) > self.backupCount:
  34.                 s.sort()
  35.                 os.remove(s[0])
  36.         #print "%s -> %s" % (self.baseFilename, dfn)
  37.         if self.encoding:
  38.             self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
  39.         else:
  40.             self.stream = open(self.baseFilename, 'w')
  41.         self.rolloverAt = self.rolloverAt + self.interval

第9行判断中只判断时间大的情况,并没有判断时间小的情况,第41行中self.rolloverAt永远是上一次的值加上self.interval,如果时间往大的调的话,第9行判断就会永远是True,所以就会产生问题,如果时间往小的调,第9行判断就会永远是False,也会产生问题。上面的python版本是2.5.4,再看最新的版本:3.1,这个版本修复了def doRollover(self),但并没有修复def shouldRollover(self, record),所以综合这两个版本的考虑,还是自己来实现吧,修复之后的代码如下(测试成功通过):

 

  1. def shouldRollover(self, record):
  2.         """
  3.         Determine if rollover should occur
  4.  
  5.         record is not used, as we are just comparing times, but it is needed so
  6.         the method siguratures are the same
  7.         """
  8.         t = int(time.time())
  9.         #print "self.rolloverAt: %d. currentTime: %d." % (self.rolloverAt, t)
  10.         #start: recompare slef.rolloverAt, Modify by 5dcode. 2012-03-14 
  11.         if t >= self.rolloverAt or t < (self.rolloverAt - self.interval):
  12.             return 1
  13.         #end: recompare slef.rolloverAt, Modify by 5dcode. 2012-03-14 
  14.         #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
  15.         return 0
  16.  
  17.     def doRollover(self):
  18.         """
  19.         do a rollover; in this case, a date/time stamp is appended to the filename
  20.         when the rollover happens.  However, you want the file to be named for the
  21.         start of the interval, not the current time.  If there is a backup count,
  22.         then we have to get a list of matching filenames, sort them and remove
  23.         the one with the oldest suffix.
  24.         """
  25.         self.stream.close()
  26.         # get the time that this sequence started at and make it a TimeTuple
  27.         t = self.rolloverAt - self.interval
  28.         timeTuple = time.localtime(t)
  29.         dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
  30.         if os.path.exists(dfn):
  31.             os.remove(dfn)
  32.         os.rename(self.baseFilename, dfn)
  33.         if self.backupCount > 0:
  34.             # find the oldest log file and delete it
  35.             s = glob.glob(self.baseFilename + ".20*")
  36.             if len(s) > self.backupCount:
  37.                 s.sort()
  38.                 os.remove(s[0])
  39.         #print "%s -> %s" % (self.baseFilename, dfn)
  40.         if self.encoding:
  41.             self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
  42.         else:
  43.             self.stream = open(self.baseFilename, 'w')
  44.         
  45.         #start: recompute self.rolloverAt, Modify by 5dcode. 2012-03-14 
  46.         currentTime = int(time.time())
  47.         newRolloverAt = currentTime + self.interval
  48.         if self.when == 'MIDNIGHT' or self.when.startswith('W'):
  49.             # This could be done with less code, but I wanted it to be clear
  50.             t = time.localtime(currentTime)
  51.             currentHour = t[3]
  52.             currentMinute = t[4]
  53.             currentSecond = t[5]
  54.             # r is the number of seconds left between now and midnight
  55.             r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
  56.                     currentSecond)
  57.             newRolloverAt = currentTime + r
  58.         #newRolloverAt = self.computeRollover(currentTime)
  59.         while newRolloverAt <= currentTime:
  60.             newRolloverAt = newRolloverAt + self.interval
  61.         #If DST changes and midnight or weekly rollover, adjust for this.
  62.         if self.when == 'MIDNIGHT' or self.when.startswith('W'):
  63.             dstNow = time.localtime(currentTime)[-1]
  64.             dstAtRollover = time.localtime(newRolloverAt)[-1]
  65.             if dstNow != dstAtRollover:
  66.                 if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
  67.                     newRolloverAt = newRolloverAt - 3600
  68.                 else:           # DST bows out before next rollover, so we need to add an hour
  69.                     newRolloverAt = newRolloverAt + 3600
  70.         self.rolloverAt = newRolloverAt
  71.         #print "self.rolloverAt: %d." % self.rolloverAt
  72.         #end: recompute self.rolloverAt, Modify by 5dcode. 2012-03-14

 

 

 

 

这篇关于python的logging库中TimedRotatingFileHandler类问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/397941

相关文章

python中各种常见文件的读写操作与类型转换详细指南

《python中各种常见文件的读写操作与类型转换详细指南》这篇文章主要为大家详细介绍了python中各种常见文件(txt,xls,csv,sql,二进制文件)的读写操作与类型转换,感兴趣的小伙伴可以跟... 目录1.文件txt读写标准用法1.1写入文件1.2读取文件2. 二进制文件读取3. 大文件读取3.1

使用Python实现一个优雅的异步定时器

《使用Python实现一个优雅的异步定时器》在Python中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

基于Python实现读取嵌套压缩包下文件的方法

《基于Python实现读取嵌套压缩包下文件的方法》工作中遇到的问题,需要用Python实现嵌套压缩包下文件读取,本文给大家介绍了详细的解决方法,并有相关的代码示例供大家参考,需要的朋友可以参考下... 目录思路完整代码代码优化思路打开外层zip压缩包并遍历文件:使用with zipfile.ZipFil

Python处理函数调用超时的四种方法

《Python处理函数调用超时的四种方法》在实际开发过程中,我们可能会遇到一些场景,需要对函数的执行时间进行限制,例如,当一个函数执行时间过长时,可能会导致程序卡顿、资源占用过高,因此,在某些情况下,... 目录前言func-timeout1. 安装 func-timeout2. 基本用法自定义进程subp

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

Python结合PyWebView库打造跨平台桌面应用

《Python结合PyWebView库打造跨平台桌面应用》随着Web技术的发展,将HTML/CSS/JavaScript与Python结合构建桌面应用成为可能,本文将系统讲解如何使用PyWebView... 目录一、技术原理与优势分析1.1 架构原理1.2 核心优势二、开发环境搭建2.1 安装依赖2.2 验

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

Python运行中频繁出现Restart提示的解决办法

《Python运行中频繁出现Restart提示的解决办法》在编程的世界里,遇到各种奇怪的问题是家常便饭,但是,当你的Python程序在运行过程中频繁出现“Restart”提示时,这可能不仅仅是令人头疼... 目录问题描述代码示例无限循环递归调用内存泄漏解决方案1. 检查代码逻辑无限循环递归调用内存泄漏2.

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化