see sharper
see sharper

Reputation: 12055

Logging an unknown exception in Python

I am getting an exception on an HTTP GET request (http.client.HTTPConnection.getresponse), but so far have been unable to determine the nature of the exception (my Python is fairly rudimentary). The code looks like this:

try:
    r = conn.getresponse()
except Exception as x:
    logger.error('Error getting data:' + str(x))

This just results in logs looking like Error getting data:''. I could trap all the different types of exception that HTTPConnection.getresponse can raise, but that seems ridiculous given there are so many possible exception types and I'm just trying to debug how the connection is failing. Is there a way to inspect the exception object?

Upvotes: 1

Views: 1043

Answers (1)

kingkupps
kingkupps

Reputation: 3534

You almost certainly want to use logger.exception if you're using Python's standard library logger which adds more info about the exception (including a call stack).

From the docs:

Logger.exception() creates a log message similar to Logger.error(). The difference is that Logger.exception() dumps a stack trace along with it. Call this method only from an exception handler.

If you want to specifically format the type of the exception in your log message, do:

try:
    r = conn.getresponse()
except Exception as e:
    logger.error('%s: %s', type(e), e)

Upvotes: 2

Related Questions