12

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?

2
  • 3
    logging.exception, per the docs, "should only be called from an exception handler." What exception are you trying to log? Commented Nov 5, 2018 at 21:59
  • @jonrsharpe Huh, the docs are actually kinda wrong here. It's supported to use logging.exception and logging.error passing in an exception instance (or a tuple), but they didn't document that. Looks like support was added in Python 3 but the docs weren't updated from 2.7 versions. Commented Nov 5, 2018 at 22:14

1 Answer 1

25

Usually, a logger.exception method would be called from within an except block. Stdlib logging is trying to append the exception info, but you don't have any exception info available because you're not logging from within an except block.

The NoneType: None output ultimately comes from the result of a sys.exc_info() call, which returns (None, None, None) for the type, value, and traceback. The logging module doesn't bother to check whether they're valid or not.

Lame workaround: suppress the exception info detail with exc_info=False

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

Slightly less lame: don't use logger.exception when there is no exception

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

Best: use logger.exception from within an exception handler

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

If you have an exception instance that was caught earlier which you want to log, and you're not within an except block, passing the exception instance explicitly will do the right thing:

try:
    # risky code
except Exception as err:
    myerror = err
# other code
logger.exception('this is an exception', exc_info=myerror)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.