Maxim Veksler Maxim Veksler - 1 year ago 72
Python Question

How to log python exception?

Coming from java, being familiar with logback I used to do

try {
catch (Exception e) {
log("Error at X", e);

I would like the same functionality of being able to log the exception and the stacktrace into a file.

How would you recommend me implementing this?

Currently using boto logging infrastructure,

I've looked at some options and found out I can access the actual exception details using this code:

import sys
import traceback

exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)

I would like to somehow get the string
throws to stdout so that I can log it.

Answer Source

To answer your question, you can get the string version of print_exception() using the traceback.format_exception() function. It returns the traceback message as a list of strings rather than printing it to stdout, so you can do what you want with it. For example:

import sys
import traceback

except NameError:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
    print ''.join('!! ' + line for line in lines)  # Log it or whatever here

This displays:

!! Traceback (most recent call last):
!!   File "<stdin>", line 2, in <module>
!! NameError: name 'asdf' is not defined

However, I'd definitely recommend using the standard Python logging module, as suggested by rlotun. It's not the easiest thing to set up, but it's very customizable.