I\'m writing a custom logging system for a project. If a function throws an exception, I want to log its local variables. Is it possible to access the raising function\'s
You can look up the local variables in the frame object, which you can get from sys.exc_info
.
>>> import sys
>>> def f(a):
... b = a - 1
... print 1.0 / b
...
>>> try:
... f(1)
... except Exception, e:
... print sys.exc_info()[2].tb_next.tb_frame.f_locals
...
{'a': 1, 'b': 0}
You'll have to include the appropriate number of tb_next
s depending on from how deep in the stack the exception was thrown.