Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logging exceptions in Python 3

I have the following :

### running with Python 3 
import logging 
logger = logging.getLogger(__name__)                                                                                                              
logger.setLevel('DEBUG')                                                                           
logger.exception('this is an exception')                                  

The output is:

this is an exception
NoneType: None

What do i need to do to get rid of that "NoneType: None" output?

like image 975
Andrew Avatar asked Nov 05 '18 21:11

Andrew


1 Answers

stdlib logging is trying to append the exception info, but you don't have any exception info because you're not logging from within an except: block. The NoneType: None ultimately come from the result of a sys.exc_info() call, logging doesn't bother to check whether they're valid or not.

Lame workaround:

logger.exception('this is an exception', exc_info=False)

Slightly less lame:

logger.error('this is an exception...haha not really')

Best:

try:
    # risky code
except Exception:
    logger.exception('this is an exception')

If you have an exception instance that was caught earlier, and you want to log it, and you're not in an except block, this will do the right thing:

logger.exception('this is an exception', exc_info=myerror)
like image 69
wim Avatar answered Nov 12 '22 10:11

wim