0

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)
0

2 Answers 2

1

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)!

Sign up to request clarification or add additional context in comments.

1 Comment

OK, I'll try it out, I didn't know info. on the current exception (if more than one possible caught) would be logged.
0

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.

3 Comments

exception(...), or more exactly, the exc_info=True parameter, includes the exception information from sys.exc_info() so that the logger implementation can use it. So why to format manually?
That was intended more for general exception handling logic, in case something useful could be done with the info. No, there's no reason to pull that out of exc_info if all you're going to do is format it into the log message.
I meant that 'message %s' % e should not be used with the logging.exception call because the exception information is stored automatically and used by the configured logger implementation in order to log the stacktrace, for example. No need to format it yourself.

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.