Python log level cannot be set

Question:

Here is my code

logger = logging.getLogger("JarvisAI")
# Create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler(logname)
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.INFO)

# Create formatters and add it to handlers
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S")
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S")
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)

# Add handlers to the logging
logger.addHandler(c_handler)
logger.addHandler(f_handler)

Running logger.info("Test") does not produce anything in the logfile.
However logger.warning and other higher log level works fine both in console and file.
Pls help.

Asked By: HilFing_Real

||

Answers:

The logger itself also has a logging level, and that needs to be below (or above, depending on your point of view) that of the handlers to show the handlers’ output:

logger.setLevel(logging.INFO)

(or even debug level: the formatters’ levels will prevent debugging info from being output anyway) will do that.

This is also shown in the first code block of the Python logging cookbook. Have a read through it.

The reason you are getting warning and higher log level output, is because warning is the default logging level.

Answered By: 9769953
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.