在Python中查找原始异常的模块名称
示例:
>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
在上面的示例中,异常实际上是在 myapp/util/url.py 模块中抛出的。 有没有办法获取该模块的 __name__ ?
我的目的是在logging.getLogger函数中使用它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这应该有效:
编辑:Stephan202 提到了一个极端情况。 在这种情况下,我认为我们可以默认文件名。
问题是,如果模块未加载(因为读取该文件中的代码时引发异常),则
inspect.getmodule
调用将返回 None。 因此,我们只使用有问题的框架引用的文件的名称。 (感谢您指出这一点,Stephan202!)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!)您可以使用 traceback 模块 以及
sys.exc_info()
,以编程方式获取回溯:You can use the traceback module, along with
sys.exc_info()
, to get the traceback programmatically:这应该可以解决问题:
This should do the trick:
Python 的日志记录包已支持此功能 - 请查看文档。 您只需在格式字符串中指定
%(module)s
即可。 但是,这会为您提供捕获异常的模块 - 不一定与引发异常的模块相同。 当然,回溯可以为您提供引发异常的精确位置。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.我在公司博客上有一个关于 CrashKit 如何从 Python 堆栈跟踪计算类名和包名的故事:“Python 堆栈跟踪传奇”。 包括工作代码。
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.