【问题标题】:Logging to python file doesn't overwrite file when using the mode='w' argument to FileHandler使用 FileHandler 的 mode='w' 参数时,记录到 python 文件不会覆盖文件
【发布时间】: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 有关。您知道是否可以永久覆盖日志记录模块的基本行为?
  • 我不知道怎么做,但不代表不可能,

标签: python logging


【解决方案1】:

这为我解决了问题:

handler = logging.FileHandler(log_filename, 'w+')

【讨论】:

    【解决方案2】:

    我对此不太熟悉,我并没有真正看到任何在谷歌中突出的东西。您是否尝试过使用:

        handler=logging.FileHandler(log_filename, 'w')
    

    【讨论】:

    • 谢谢,但它的行为方式相同。
    【解决方案3】:

    问题是文件实际上并没有被覆盖,直到一个新的 python shell 启动。

    【讨论】:

      猜你喜欢
      • 2010-10-26
      • 2014-08-02
      • 2022-01-12
      • 2019-01-02
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      相关资源
      最近更新 更多