Python logger not printing Info

Viewed 10829

Looking at the python docs, if I set my logger level to INFO, it should print out all logs at level INFO and above.

However, the code snipper below only prints "error"

import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info("Info")
logger.error("error")
logger.info("info")

Output

error

What could be the reason for this?

2 Answers

Use logging.basicConfig to set a default level and a default handler:

import logging

logger = logging.getLogger()
logging.basicConfig(level=logging.INFO)

logger.info("Info")
logger.error("error")
logger.info("info")

prints:

INFO:root:Info
ERROR:root:error
INFO:root:info

The logging module is powerful yet confusing. Look into the HOWTO in the docs for a tutorial. I've made my own helper function that logs to stderr and a file that I've detailed on my blog. You might like to adapt it to your needs.

The reason for this behaviour is that there are no logging handlers defined. In this case the handler "logging.lastResort" is used. Per default this handler is "<_StderrHandler (WARNING)>". It logs to stderr but only starting from level "WARNING".

For your example you could do the following (logging to stdout):

import logging
import sys
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.info("info")

Output

info

In the howto you can find other useful handlers.

Related