【发布时间】:2016-07-16 08:57:25
【问题描述】:
我有一些代码可以在 Python 2.7 中设置日志(使用日志记录模块):
import os
import logging
logger=logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
log_filename=os.path.join(os.path.dirname(copasi_file),os.path.split(copasi_file)[1][:-4]+'_log.log')
handler=logging.FileHandler(log_filename,mode='w')
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.debug('debugging message')
此代码有效并且我正在获取输出,但是我打算使用此日志进行大量调试,因此我想在每次运行时覆盖日志文件。在 docs 中说要使用 mode 关键字参数到 'FileHandler. It doesn't specify precisely *which* mode to use for overwrite file each time but I think a reasonable assumption would bemode='w'`。然而这不起作用。谁能告诉我为什么?
【问题讨论】:
-
我无法重现该行为。我使用了您提供的代码,只是更改了文件名,每次运行代码时都会覆盖日志。如果我将
mode更改为a,那么新运行会将行添加到末尾, -
这很奇怪,可能与我之前的question 有关。您知道是否可以永久覆盖日志记录模块的基本行为?
-
我不知道怎么做,但不代表不可能,