如何记录Python异常?
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
如何记录Python异常?
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
当前回答
我就是这么做的。
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
import traceback
traceback.format_exc() # this will print a complete trace to stout.
其他回答
下面是一个简单的例子,摘自python 2.6文档:
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
logging.debug('This message should go to the log file')
使用日志记录。Exception:处理程序/块中的异常,以记录当前异常和跟踪信息,并添加一条消息。
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
logging.debug('This message should go to the log file')
try:
run_my_stuff()
except:
logging.exception('Got exception on main handler')
raise
现在查看日志文件/tmp/logging_example.out:
DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
File "/tmp/teste.py", line 9, in <module>
run_my_stuff()
NameError: name 'run_my_stuff' is not defined
未捕获的异常消息将发送到STDERR,因此,您可以使用任何用于运行Python脚本的shell将STDERR发送到文件中,而不是在Python中实现日志记录。在Bash脚本中,您可以使用输出重定向来实现这一点,如Bash指南中所述。
例子
附加错误文件,其他输出到终端:
./test.py 2>> mylog.log
覆盖交错的STDOUT和STDERR输出文件:
./test.py &> mylog.log
下面是一个使用sys.excepthook的版本
import traceback
import sys
logger = logging.getLogger()
def handle_excepthook(type, message, stack):
logger.error(f'An unhandled exception occured: {message}. Traceback: {traceback.format_tb(stack)}')
sys.excepthook = handle_excepthook
使用exc_info选项可能更好,保留警告或错误标题:
try:
# coode in here
except Exception as e:
logging.error(e, exc_info=True)