Example:
>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the __name__
of that module?
My intention is to use this in logging.getLogger
function.
This should do the trick:
This should work:
EDIT: Stephan202 mentions a corner case. In this case, I think we could default to the file name.
The problem is that if the module doesn't get loaded (because an exception was thrown while reading the code in that file), then the
inspect.getmodule
call returns None. So, we just use the name of the file referenced by the offending frame. (Thanks for pointing this out, Stephan202!)I have a story about how CrashKit computes class names and package names from Python stack traces on the company blog: “Python stack trace saga”. Working code included.
You can use the traceback module, along with
sys.exc_info()
, to get the traceback programmatically:Python's logging package already supports this - check the documentation. You just have to specify
%(module)s
in the format string. However, this gives you the module where the exception was caught - not necessarily the same as the one where it was raised. The traceback, of course, gives you the precise location where the exception was raised.