Logging Exceptions in Python

Your code is crashing and that’s a good thing, cuz something bad has happened. But how to you capture the traceback before the crash?

I can never remember the syntax for these. Here they are:

import traceback
import logging

logger = logging.getLogger('my_logger')

try:
    x = y
except:
    # If you want the exception as a string
    print 'The traceback:', traceback.format_exc()
    
    # To put the exception directly into the log file:
    logger.exception('My message: ')  # the exception will be after your message str
    
    # If you want to continue as if this exception was not here (e.g. crash), then re-raise
    raise
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s