fred basset
fred basset

Reputation: 10082

Python exception logging, correct syntax?

I'm adding logging to some python code that deals with exceptions, in the example below what's the correct syntax for wanting to log exception details (e.g. via logger.exception()) when a TypeError or AttributeError occurs?

    try:
        ...
    except (TypeError, AttributeError):
        # want to do a logger.exception(x) here but not sure what to use for x
        ...
        raise CustomError("Unable to parse column status)

Upvotes: 0

Views: 1824

Answers (2)

Ian Clelland
Ian Clelland

Reputation: 44132

If you want the exception details, you need to bind the exception itself to a local variable, like this:

except (TypeError, AttributeError), e:
    # e is the Exception object
    logger.exception(e)

If you need to do different things based on the type of the exception, then you can catch them separately:

except TypeError, e:
    logger.exception('There was a Type Error; details are %s' % e)
    # Do something, or raise another exception
except AttributeError, e:
    logger.exception('There was an Attribute Error; details are %s' % e)
    # Do something, or raise another exception

And if you need more information about the context of the exception itself, look into the sys.exc_info() function; it can get you the traceback, and the details about exactly where the exception occurred.

Upvotes: 0

AndiDog
AndiDog

Reputation: 70158

exception(...) is just a convenience method which takes a message just like the other methods:

def exception(self, msg, *args):
    """
    Convenience method for logging an ERROR with exception information.
    """
    self.error(msg, exc_info=1, *args)

So you would just use it like

logger.exception("Some error message")

and the logging handler will automatically add the exception information from the current exception. Only use this in an exception handler (i.e. in a except: block)!

Upvotes: 1

Related Questions