記錄 Python 異常的最佳方法是什麼?


我們匯入日誌模組,然後使用 logging.exception 方法建立 Python 異常日誌。

示例

import logging
try:
print 'toy' + 6
except Exception as e:
logging.exception("This is an exception log")

輸出

我們得到以下輸出

ERROR:root:This is an exception log
Traceback (most recent call last):
File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/Exception handling/loggingerror1.py", line 3, in <module>
print 'toy' + 6
TypeError: cannot concatenate 'str' and 'int' objects

需要注意的是,在 Python 3 中,我們必須在 except 部分內呼叫 logging.exception 方法。如果在這個部分的任何其他地方呼叫該方法,則可能會根據 Python 文件發出警報並收到一個奇怪的異常。

更新於:2020-02-12

347 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告