I'm working in IPython and I've noticed that the logging doesn't right until the second time I run the code. Running imp.reload(logging)
, as suggested here, doesn't solve the problem.
Here's the code:
import logging, imp
def print_handlers(text, logger):
print("{}; handlers are {}".format(text, [h.stream for h in logger.handlers]))
logger = logging.getLogger()
print_handlers("Before config", logger)
logger.error("Before config")
logging.basicConfig()
logger = logging.getLogger()
print_handlers("After basicConfig", logger)
logger.error("After basicConfig")
imp.reload(logging)
logging.basicConfig()
logger = logging.getLogger()
print_handlers("After reload and basicConfig", logger)
logger.error("After reload and basicConfig")
The first time I run this after starting a new IPython session, the following output goes to stderr in the terminal that I ran IPython from:
ERROR:root:Before config
ERROR:root:After basicConfig
ERROR:root:After reload and basicConfig
And I get this output in my IPython window:
Before config; handlers are [<_io.TextIOWrapper name='<stderr>' mode='w' encoding='ANSI_X3.4-1968'>]
After basicConfig; handlers are [<_io.TextIOWrapper name='<stderr>' mode='w' encoding='ANSI_X3.4-1968'>]
After reload and basicConfig; handlers are [<_io.TextIOWrapper name='<stderr>' mode='w' encoding='ANSI_X3.4-1968'>]
Notice that throughout the output of the logging is being directed to stderr.
Now, if I evaluate the cell with the code in it again, I get the same lines of logging, but this time they arrive in my IPython window (where I want them), not in the terminal from which I ran IPython. And the print
commands give me this:
Before config; handlers are []
After basicConfig; handlers are [<IPython.kernel.zmq.iostream.OutStream object at 0x7ffc1b308048>]
After reload and basicConfig; handlers are [<IPython.kernel.zmq.iostream.OutStream object at 0x7ffc1b308048>]
Can I get the logging to show up in IPython from the beginning, instead of having to run my code twice?
I'm using Python 3.4.2 and IPython 2.3.0.