This is how I do it:
>>> import traceback
>>> try:
... int('k')
... except:
... var = traceback.format_exc()
...
>>> print(var)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'k'
You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards...
Answer from mac on Stack OverflowThis is how I do it:
>>> import traceback
>>> try:
... int('k')
... except:
... var = traceback.format_exc()
...
>>> print(var)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'k'
You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards...
sys.exc_info() returns a tuple with three values (type, value, traceback).
- Here type gets the exception type of the Exception being handled
- value is the arguments that are being passed to constructor of exception class
- traceback contains the stack information like where the exception occurred etc.
For Example, In the following program
try:
a = 1/0
except Exception,e:
exc_tuple = sys.exc_info()
Now If we print the tuple the values will be this.
- exc_tuple[0] value will be "ZeroDivisionError"
- exc_tuple[1] value will be "integer division or modulo by zero" (String passed as parameter to the exception class)
- exc_tuple[2] value will be "trackback object at (some memory address)"
The above details can also be fetched by simply printing the exception in string format.
print str(e)
From the logging documentation:
There are three keyword arguments in
kwargswhich are inspected:exc_info,stack_info, andextra.If
exc_infodoes not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned bysys.exc_info()) or an exception instance is provided, it is used; otherwise,sys.exc_info()is called to get the exception information.
So do:
logger.warning("something raised an exception:", exc_info=True)
Here is one that works (python 2.6.5).
logger.critical("caught exception, traceback =", exc_info=True)