Jupyter notebook does not print logs to the output cell

Viewed 25710

I am currently using Jupyter notebook and I would like to force it to print out Python logs to the output cell.

I am using old notebook that used to work this way, probably in older version of Jupyter notebook.

I have logging set as:

import logging
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logging.root.level = 20

But when I then call:

logging.info("hello world")

It does not print anything in the output cell. It just prints out the stuff in the console in which I started the Jupyter notebook.

I am using python 2.7.10 and installed packages in my virtual environment are:

appnope==0.1.0
backports-abc==0.4
backports.ssl-match-hostname==3.5.0.1
certifi==2016.2.28
decorator==4.0.9
functools32==3.2.3.post2
gnureadline==6.3.3
ipykernel==4.3.1
ipython==4.1.2
ipython-genutils==0.1.0
ipywidgets==4.1.1
Jinja2==2.8
jsonschema==2.5.1
jupyter==1.0.0
jupyter-client==4.2.2
jupyter-console==4.1.1
jupyter-core==4.1.0
MarkupSafe==0.23
mistune==0.7.2
nbconvert==4.1.0
nbformat==4.0.1
notebook==4.1.0
path.py==8.1.2
pexpect==4.0.1
pickleshare==0.6
ptyprocess==0.5.1
Pygments==2.1.3
pyzmq==15.2.0
qtconsole==4.2.0
simplegeneric==0.8.1
singledispatch==3.4.0.3
six==1.10.0
terminado==0.6
tornado==4.3
traitlets==4.1.0
wheel==0.24.0

Was logging printout in the cell changed? Is there some way how I can force Jupyter to write out logging to the output cell?

5 Answers

The earlier answers seem no longer to work. The most complete one no longer works because there are no default handlers, so modifying the zeroeth doesn't work. Also, messing with the root logger seems potentially fraught when running in a notebook.

In order to get the "foo" logger to put its output in the cell you can do the following:

logger = logging.getLogger("foo")
logger.addHandler(logging.StreamHandler(stream=sys.stdout))

So add the handler yourself, and direct its output.

The solution to specify the stream works well. Another option for configuration if using the dictConfig is to add the stream as a parameter

import logging
import logging.config

logging.config.dictConfig({
    "version": 1,
    "disable_existing_loggers": True,
    "formatters": {
        "default": {
            "format": "{levelname} {asctime} | {message}",
            "style": "{",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "default",
            "stream": sys.stdout,
        }
    },
    "root": {
        "level": "DEBUG",
        "handlers": ["console"],
    },
})
Related