如何记录python异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4508849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to log python exception?
提问by Maxim Veksler
How can I log an exception in Python?
如何在 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.
我想以某种方式将字符串print_exception()抛出到标准输出,以便我可以记录它。
采纳答案by yurez
In Python 3.5 you can pass exception instance in exc_info argument:
在 Python 3.5 中,您可以在 exc_info 参数中传递异常实例:
import logging
try:
1/0
except Exception as e:
logging.error('Error at %s', 'division', exc_info=e)
回答by rlotun
Take a look at logging.exception(Python Logging Module)
看一看logging.exception(Python 日志模块)
import logging
def foo():
try:
some_code()
except:
logging.exception('')
This should automatically take care of getting the traceback for the current exception and logging it properly.
这应该自动处理获取当前异常的回溯并正确记录它。
回答by erickrf
First of all, consider using a proper Exception type on your except clause. Then, naming the exception, you can print it:
首先,考虑在您的 except 子句上使用适当的 Exception 类型。然后,命名异常,您可以打印它:
try:
1/0
except Exception as e:
print e
Dependending on your Python version, you must use
根据您的 Python 版本,您必须使用
except Exception, e
回答by Ben Hoyt
To answer your question, you can get the string version of print_exception()using the traceback.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:
要回答您的问题,您可以获得print_exception()使用该traceback.format_exception()函数的字符串版本。它将回溯消息作为字符串列表返回,而不是将其打印到标准输出,因此您可以使用它做您想做的事情。例如:
import sys
import traceback
try:
asdf
except NameError:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print ''.join('!! ' + line for line in lines) # Log it or whatever here
This displays:
这显示:
!! Traceback (most recent call last):
!! File "<stdin>", line 2, in <module>
!! NameError: name 'asdf' is not defined
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.
但是,我绝对推荐使用标准的 Python 日志记录模块,正如 rlotun 所建议的那样。这不是最容易设置的事情,但它非常可定制。
回答by NeilenMarais
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.
记录异常就像将 exc_info=True 关键字参数添加到任何日志消息一样简单,请参阅http://docs.python.org/2/library/logging.html 中的Logger.debug 条目。
Example:
例子:
try:
raise Exception('lala')
except Exception:
logging.info('blah', exc_info=True)
output (depending, of course, on your log handler config):
输出(当然,取决于您的日志处理程序配置):
2012-11-29 10:18:12,778 - root - INFO - <ipython-input-27-5af852892344> : 3 - blah
Traceback (most recent call last):
File "<ipython-input-27-5af852892344>", line 1, in <module>
try: raise Exception('lala')
Exception: lala

