Python logging exception

There is nothing wrong with catching to log. However, I’d recommend:

    try:
        response = self.call_api_method()
    except APIException, e:  # or 'as e' depending on your Python version
        self.log.exception('Oh noes!')
        raise #Throw exception again so calling code knows it happened
    else:
        return response.someData

By just doing a bare raise you preserve the full traceback info. It’s also more explicit to put code that will only happen if you don’t have an exception in the else clause, and it’s clearer what line you’re catching an exception from.

It would also be fine for the calling class to do the logging if it’s handling the error anyway, but that may not be convenient for your app.

Edit: The documentation for try ... except ... else ... finally is under compound statements.

Leave a Comment