Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 & PyCharm - Debug logging levels in run/debug

Tags:

I'm just starting with PyCharm, is there a way to show debug & info warnings?

import logging logger = logging.getLogger('tipper') logger.setLevel(logging.DEBUG) logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message') 

warn, error, critical all show:

/home/username/someproject/.someprojectenv/bin/python3/home/username/someproject/go.py warn message error message critical message  Process finished with exit code 0 

However debug, info do not show.

like image 430
Josh Avatar asked Mar 24 '14 14:03

Josh


Video Answer


1 Answers

The problem has nothing to do with PyCharm, but with how logging configuration works. If you try to write the code you have shown in a normal python interactive session you get the same output:

>>> import logging >>> logger = logging.getLogger('tipper') >>> logger.setLevel(logging.DEBUG) >>> logger.debug('debug message') >>> logger.info('info message') >>> logger.warn('warn message') warn message >>> logger.error('error message') error message >>> logger.critical('critical message') critical message 

The problem is that setting the logger's level isn't enough! You must also add a handler to the logger otherwise the logger will simply forward the message up the chain. The messages will end up at the root logger, which has, by default, a level of logging.WARN and thus discards DEBUG level messages.

However if you add a handler to logger all works fine:

>>> logger.addHandler(logging.StreamHandler()) >>> logger.debug('test') test 

You can set more than one handler for each logger and each handler can have a different logging level.

See this question for a bit of further information about logger's and handler's levels. I'd suggest also to read carefully the documentation for the logging module and the various guides (e.g. the logging How-To, because it has a really advanced configuration.

Also from python3.2 there's a dictConfig function which allow you to specify the configuration for your logging hierarchy as dictionary, without having to manually create every handler and logger by hand.

like image 140
Bakuriu Avatar answered Oct 18 '22 05:10

Bakuriu