简体   繁体   English

python日志记录没有保存到文件

[英]python logging not saving to file

I have been stuck on this for the past hour. 过去一小时我一直坚持这一点。 I had plugged logging into my tkinter gui, but could not get it to work. 我已经插入登录到我的tkinter gui,但无法让它工作。 I then started removing parts until I got at the bare bones example in the very python docs and it will not work. 然后我开始删除部分,直到我在非常python文档中的裸骨示例,它将无法正常工作。 At this point I have nothing else to remove. 在这一点上,我没有别的东西要删除。

The code is as follows: 代码如下:

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)

The warning is printed to stdout, but the file is not generated. 警告将打印到stdout,但不会生成该文件。 I am runing python 3.4, x64 on a windows 7. It is a anacondas distribution, so this is running in Ipython inside spyder. 我在Windows 7上运行python 3.4,x64。它是一个anacondas发行版,所以这是在Spyder里面的Ipython中运行的。

I guess this should be working 我想这应该有效

As Jonas Byström noted, this does work outside Ipython. 正如JonasByström所说,这在Ipython之外有效。 It seems that Ipython configures a logging handler before I get the chance to do so. 似乎Ipython在我有机会之前配置了一个日志记录处理程序。 Also, basicConfig will do nothing if a handler is already present. 此外,如果处理程序已存在, basicConfig将不执行任何操作。 So, in order to have it working in Ipython, one must do one of three things: 1) Add a new handler, OR 2)reload logging, OR 3) remove existing handlers. 因此,为了让它在Ipython中工作,必须做以下三件事之一:1)添加新的处理程序,或者2)重新加载日志记录,或者3)删除现有的处理程序。 I did number 2 bellow. 我做了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)

See theese for more information: Logging in ipython ; 有关更多信息,请访问theese登录ipython ; More on the same 更多相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM