【问题标题】:python logging.basicConfig doesn't overwrite the existing log filepython logging.basicConfig 不会覆盖现有的日志文件
【发布时间】:2020-08-08 20:17:17
【问题描述】:

我正在使用 python 的 logging.basicConfig 方法,向它传递一些参数,包括 filemode = "w"。如果未指定,则默认为“a”,追加。但是,尽管指定它来覆盖现有的日志文件,它仍然是附加的。我在 anaconda 上使用 python 3。任何帮助表示赞赏:)

import logging
# add filemode "w" to overwrite
logging.basicConfig(filename = "sample.log", level = logging.INFO,filemode = "w" )
logging.debug("This is a debug message")
logging.info("Informational message")
logging.error("An error has happened!")```

【问题讨论】:

  • 我试过你的代码,对我来说很好,当filemode = "w"时它会覆盖日志文件
  • 一天后我一次又一次地尝试,但没有发生任何新情况。它一直在附加。最后我把日志部分扔掉了!

标签: python python-3.x logging anaconda overwrite


【解决方案1】:

就我而言: Google Colab 中的同样问题: logging.basicConfig(filename="log_file", filemode='w', level=logging.DEBUG) 代码确实附加了log_file,而不是覆盖...

我提前为这个重要信息道歉 - 我试图澄清情况的所有要点。我将立即预订在 PyCharm 中运行脚本时不会观察到这种效果。 我想问题出在 Anaconda 中(类似于 Google Colab,我遇到了同样的问题),代码不是重新执行,而是使用以前执行的结果。从程序启动的那一刻起,根据意识形态的日志记录过程就可以随时使用。这可能就是为什么有一个规则:(PEP: 282, part "Loggers") *"... 否则, 如果存在具有该名称的记录器,则返回。如果没有,新的 logger已初始化并返回... "*在我们的例子中,我们需要重新启动内核以清除存储日志的文件的内容。为了好奇,我会尝试在不重启Kernel的情况下重置日志的存储,但这已经是异常模式了。

https://github.com/python/peps/blob/master/pep-0282.txt#L220

【讨论】:

  • 这并不能真正回答问题。如果您有其他问题,可以点击 提问。一旦你有足够的reputation,你也可以add a bounty 来引起对这个问题的更多关注。 - From Review
  • 已修复,我希望现在该消息将有助于找到问题的解决方案。
【解决方案2】:

使用下面的代码试试 -

filemode = "w+"

logging.basicConfig(filename = "sample.log", level = logging.INFO,filemode = "w+" )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2019-09-30
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多