import logging
try:1/0except BaseException:logging.exception("An exception was thrown!")
产出
ERROR:root:An exception was thrown!Traceback (most recent call last):File ".../Desktop/test.py", line 4, in <module>1/0ZeroDivisionError: division by zero
logging.critical("An exception was thrown!", exc_info=True)logging.error ("An exception was thrown!", exc_info=True)logging.warning ("An exception was thrown!", exc_info=True)logging.info ("An exception was thrown!", exc_info=True)logging.debug ("An exception was thrown!", exc_info=True)
# or the general formlogging.log(level, "An exception was thrown!", exc_info=True)
with open("not_existing_file.txt", 'r') as text:pass
将产生以下回溯:
Traceback (most recent call last):File "exception_checks.py", line 19, in <module>with open("not_existing_file.txt", 'r') as text:FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
打印/记录完整的追溯
正如其他人已经提到的,您可以使用traceback模块捕获整个回溯:
import tracebacktry:with open("not_existing_file.txt", 'r') as text:passexcept Exception as exception:traceback.print_exc()
这将产生以下输出:
Traceback (most recent call last):File "exception_checks.py", line 19, in <module>with open("not_existing_file.txt", 'r') as text:FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
您可以通过使用日志来实现相同的目的:
try:with open("not_existing_file.txt", 'r') as text:passexcept Exception as exception:logger.error(exception, exc_info=True)
输出:
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'Traceback (most recent call last):File "exception_checks.py", line 27, in <module>with open("not_existing_file.txt", 'r') as text:FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
仅打印/记录错误名称/消息
您可能对整个回溯不感兴趣,但只对最重要的信息(例如异常名称和异常消息)感兴趣,请使用:
try:with open("not_existing_file.txt", 'r') as text:passexcept Exception as exception:print("Exception: {}".format(type(exception).__name__))print("Exception message: {}".format(exception))
输出:
Exception: FileNotFoundErrorException message: [Errno 2] No such file or directory: 'not_existing_file.txt'