加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 日志记录,处理文件翻转时丢失的日志文件

发布时间:2020-12-20 13:36:58 所属栏目:Python 来源:网络整理
导读:有人无意中移动了 python程序使用的打开日志文件. 该程序使用带有TimedRotatingFileHandler的日志记录模块.当翻转文件的时候输出了这个错误: Traceback (most recent call last):File "/python_root/lib/logging/handlers.py",line 78,in emit self.doRollo
有人无意中移动了 python程序使用的打开日志文件.
该程序使用带有TimedRotatingFileHandler的日志记录模块.当翻转文件的时候输出了这个错误:

Traceback (most recent call last):
File "/python_root/lib/logging/handlers.py",line 78,in emit
    self.doRollover()
  File "/python_root/lib/logging/handlers.py",line 338,in doRollover
    os.rename(self.baseFilename,dfn)
OSError: [Errno 2] no such file or directory
Logged from file logtest.py,line 16

每次后续尝试记录某些内容时都会重复该错误.记录的消息未进入旧的(移动的)日志文件.

这再现了问题(如果您移动日志文件:))

import time
import logging
from logging import handlers

f = logging.Formatter( "%(asctime)s %(message)s" )
h = handlers.TimedRotatingFileHandler(
      "testlog",when='s',interval=5,backupCount=10 )
h.setFormatter( f )
logger = logging.getLogger( 'test' )
logger.setLevel( logging.INFO )
logger.addHandler( h )
logger.info( "LOGTEST started" )
for i in range( 10 ):
    time.sleep( 5 )
    logger.info( "Test logging " + str( i ) )

我担心的是后续的日志消息丢失了.我想要实现的是按优先顺序升序:

>退出的例外.
>我能抓住并处理的例外.
>记录器显示错误,但后续消息将转到旧日志文件.
>记录器显示此错误,但会打开一个新的日志文件并继续正常运行.

我已经浏览了相关钩子的文档/食谱,但没有任何东西突然出现在我面前.指针也同样受欢迎.

谢谢你的帮助,

乔纳森

解决方法

在doRollover中引发的异常将传递给处理程序的handleError方法.您可以定义子类并覆盖此方法,以执行您要执行的任何操作来处理错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读