我有一个python3.4应用程序,它广泛使用日志记录。我注册了两个FileHandler和一个StreamHandler。一切都如预期的那样工作,除了有时,requests
库抛出异常之后,日志文件会丢失所有累积的消息并以新消息开始。我假设由于某种原因,FileHandlers用mode='w'
重新打开了文件,但我不明白为什么。有什么想法吗?在
程序如下:
# Set up root logger - two handlers logging to files
fh_debug = logging.FileHandler('Syncer.debug', mode='w', encoding='utf-8')
fh_debug.setLevel(logging.DEBUG)
fh_log = logging.FileHandler('Syncer.log', mode='w', encoding='utf-8')
fh_log.setLevel(logging.INFO)
fh_formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
fh_debug.setFormatter(fh_formatter)
fh_log.setFormatter(fh_formatter)
logging.getLogger().addHandler(fh_debug)
logging.getLogger().addHandler(fh_log)
# Add console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch_formatter = logging.Formatter('%(message)s')
ch.setFormatter(ch_formatter)
logging.getLogger().addHandler(ch)
# Need to set the logging level of the logger as well as the handlers
logging.getLogger().setLevel(logging.DEBUG)
# Set up the logger for this module
logger = logging.getLogger("Syncer")
logger.debug('Logger started.')
模块只包含
^{pr2}$
您的问题是您为您的
FileHandler
选择了错误的mode
。在FileHandler
的默认模式是a
,这意味着向日志文件追加新行。在您将默认模式修改为
w
,该模式将文件截断为零长度或创建一个新的文件进行写入。这就是为什么你丢失了所有累积的信息。在将其更改为
mode='a'
或只删除mode='w'
,然后您的记录器就可以工作了。阅读official python docs here
相关问题 更多 >
编程相关推荐