如何在 Python 中自動記錄未捕獲的異常?

Patricia Arquette
發布: 2024-10-22 23:00:29
原創
299 人瀏覽過

How Can I Automatically Log Uncaught Exceptions in Python?

在 Python 中記錄未捕獲的異常

捕獲和處理異常對於 Python 中的錯誤處理至關重要。但是,如果未捕獲的異常會列印到標準錯誤輸出 (stderr),該怎麼辦?

自訂異常處理

雖然總是建議明確捕獲和處理異常,但有時可能會方便自動記錄未捕獲的異常。以下解決方案不依賴try/ except 區塊,而是允許自動進行日誌記錄:

<code class="python">import sys
import logging

# Create a custom exception handler
def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    # Use the logging module to handle the uncaught exception
    logger = logging.getLogger(__name__)
    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

# Replace the default exception handler with our custom one
sys.excepthook = handle_exception

# Set up a logger and handler
logger = logging.getLogger(__name__)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

# Raise an exception to test the custom exception handling
if __name__ == "__main__":
    raise RuntimeError("Test unhandled")</code>
登入後複製

說明

此程式碼完成多項任務:

  • 建立一個自訂異常處理函數(handle_exception),它接受標準異常參數(exc_type、exc_value和exc_traceback)。
  • 在handle_exception內,程式碼忽略KeyboardInterrupt異常(因此您可以使用Ctrl C正常退出程式)。
  • 使用日誌記錄模組記錄未捕獲的異常,並帶有自訂訊息「未捕獲的異常」和異常詳細資訊。
  • 自訂異常處理程序被註冊為預設異常處理程序,取代 Python 的異常處理程序列印到 stderr 的預設行為。

透過自動記錄未捕獲的異常,此方法簡化了錯誤處理,並提供了一個中心位置來檢查程式執行期間​​發生的所有異常,無論它們是否被捕獲.

以上是如何在 Python 中自動記錄未捕獲的異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!