This question already has an answer here:
How can I log an exception in Python?
I've looked at some options and found out I can access the actual exception details using this code:
import sys
import traceback
try:
1/0
except:
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 print_exception()
throws to stdout so that I can log it.
Take a look at
logging.exception
(Python Logging Module)This should automatically take care of getting the traceback for the current exception and logging it properly.
To answer your question, you can get the string version of
print_exception()
using thetraceback.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:This displays:
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.
In Python 3.5 you can pass exception instance in exc_info argument:
Logging exceptions is as simple as adding the exc_info=True keyword argument to any log message, see entry for Logger.debug in http://docs.python.org/2/library/logging.html.
Example:
output (depending, of course, on your log handler config):
First of all, consider using a proper Exception type on your except clause. Then, naming the exception, you can print it:
Dependending on your Python version, you must use