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

相关文章

基于Linux的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

Python打印对象所有属性和值的方法小结

《Python打印对象所有属性和值的方法小结》在Python开发过程中,调试代码时经常需要查看对象的当前状态,也就是对象的所有属性和对应的值,然而,Python并没有像PHP的print_r那样直接提... 目录python中打印对象所有属性和值的方法实现步骤1. 使用vars()和pprint()2. 使

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.