【问题标题】:python logging not saving to filepython日志记录不保存到文件
【发布时间】:2015-09-19 02:17:42
【问题描述】:

在过去的一个小时里,我一直被困在这个问题上。我已将登录插入到我的 tkinter gui,但无法使其正常工作。然后我开始删除部分,直到我在非常 python 文档中得到了最简单的例子,它不会工作。在这一点上,我没有其他要删除的内容。

代码如下:

import logging

LOG_FILENAME = r'logging_example.out'


logging.basicConfig(filename=LOG_FILENAME ,level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

f = open(LOG_FILENAME, 'rt')
try:
    body = f.read()
finally:
    f.close()

print('FILE:')
print (body)

警告会打印到标准输出,但不会生成文件。 我在 Windows 7 上运行 python 3.4、x64。它是 anacondas 发行版,所以它在 spyder 内的 Ipython 中运行。

我想这应该可以工作

【问题讨论】:

  • 这在从 shell 运行 python.exe 时有效。必须与您的环境有关。

标签: python logging


【解决方案1】:

正如 Jonas Byström 所指出的,这在 Ipython 之外确实有效。在我有机会这样做之前,Ipython 似乎配置了一个日志记录处理程序。此外,如果处理程序已经存在,basicConfig 将不执行任何操作。所以,为了让它在 Ipython 中工作,必须做以下三件事之一:1)添加一个新的处理程序,或者 2)重新加载日志记录,或者 3)删除现有的处理程序。我做了下面的第 2 条。

import logging
from imp import reload
reload(logging)
LOG_FILENAME = r'logging_example.out'


logging.basicConfig(filename=LOG_FILENAME ,level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

f = open(LOG_FILENAME, 'rt')
try:
    body = f.read()
finally:
    f.close()

print('FILE:')
print (body)

有关详细信息,请参阅这些: Logging in ipython; More on the same

【讨论】:

  • 我也更喜欢选项 2,因为它很简单,可以让我更好地控制所有日志记录行为。 +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
  • 2019-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多