为什么Python日志框架会丢失消息?

2024-05-15 09:46:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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}$

Tags: thedebuglogmodeformatterloggingchlogger
1条回答
网友
1楼 · 发布于 2024-05-15 09:46:47

您的问题是您为您的FileHandler选择了错误的mode。在

FileHandler的默认模式是a,这意味着向日志文件追加新行。在

class logging.FileHandler(filename, mode='a', encoding=None, delay=False)

您将默认模式修改为w,该模式将文件截断为零长度或创建一个新的文件进行写入。这就是为什么你丢失了所有累积的信息。在

将其更改为mode='a'或只删除mode='w',然后您的记录器就可以工作了。

阅读official python docs here

相关问题 更多 >