日志记录模块无法在IPython中打印 [英] Logging module does not print in IPython

查看:116
本文介绍了日志记录模块无法在IPython中打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码的确在"ipython qtconsole"中打印了我要打印",但是在普通的IPython中却不打印.

The following code does print 'I want this to print' in 'ipython qtconsole', however it does not print in plain IPython.

import logging
import logging.handlers

log = logging.getLogger()
f = logging.Formatter("%(asctime)s - %(module)s.   %(funcName)s - %(levelname)s - %(message)s")
fh = logging.handlers.TimedRotatingFileHandler('log.txt', 'W6')
fh.setFormatter(f)
log.addHandler(fh)
log.setLevel(logging.INFO)
log.info('I want this to print')

但是在"IPython qtconsole"中,我遇到了不同的问题,我试图解释

In 'IPython qtconsole' however i get different problems, that i tried to explain here (which did not go so well, no need to read!).

你能告诉我为什么吗?

我使用Python 2.7

I use Python 2.7

也许我真的只需要添加logging.StreamHandler.

Maybe i really just need to add logging.StreamHandler.

推荐答案

似乎qtconsoleroot记录器添加了处理程序:

It seems like qtconsole adds an handler to the root logger:

In [1]: import logging
   ...: root = logging.getLogger()
   ...: root.handlers
   ...: 
Out[1]: [<logging.StreamHandler at 0x7fd8e00e1f98>]

使用普通的python解释器或仅ipython:

While using the normal python interpreter or just ipython:

In [1]: import logging

In [2]: root = logging.getLogger()

In [3]: root.handlers
Out[3]: []

如果您希望两者的行为相同,则应将StreamHandler添加到普通ipython的根记录器中,或从qtconsole解释器中删除StreamHandler.

If you want both to behave the same you should either add a StreamHandler to the root logger for normal ipython, or remove the StreamHandler from the qtconsole interpreter.

如果希望前者只需添加:

If you want the former just add:

root = logging.getLogger()
root.addHandler(logging.StreamHandler())

如果要使用后者,请之前添加自己的处理程序,请执行以下操作:

If you want the latter, before adding your own handler, do:

for handler in root.handlers[:]:
    root.removeHandler(handler)


请注意,IPython已经提供了一些用于登录文件的机制.请参阅文档.如果您只想在ipython内部使用代码,使用它的魔力可能会更简单.


Note that IPython already provides some machinery for logging to a file. See the documentation. If you want to use the code only inside ipython using its magics might be simpler.

这篇关于日志记录模块无法在IPython中打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆