logging_error.py
· 537 B · Python
原始檔案
# 首先,引入 logging 模組
import logging
# 然後,建立一個 logfile,用來記錄錯誤訊息
logging.basicConfig(filename="error.log", level=logging.ERROR)
# 接下來,在你的程式中,當發生錯誤時,使用 logging.error() 來記錄錯誤訊息
# 同時,把 backtrace 設定為 True,以便在錯誤發生時記錄回溯訊息
try:
# 這裡是你的程式碼
# 假設有一個除數為 0 的情況
result = 1 / 0
except Exception as e:
logging.error("錯誤發生:%s" % e, exc_info=True)
| 1 | # 首先,引入 logging 模組 |
| 2 | import logging |
| 3 | |
| 4 | # 然後,建立一個 logfile,用來記錄錯誤訊息 |
| 5 | logging.basicConfig(filename="error.log", level=logging.ERROR) |
| 6 | |
| 7 | # 接下來,在你的程式中,當發生錯誤時,使用 logging.error() 來記錄錯誤訊息 |
| 8 | # 同時,把 backtrace 設定為 True,以便在錯誤發生時記錄回溯訊息 |
| 9 | try: |
| 10 | # 這裡是你的程式碼 |
| 11 | # 假設有一個除數為 0 的情況 |
| 12 | result = 1 / 0 |
| 13 | except Exception as e: |
| 14 | logging.error("錯誤發生:%s" % e, exc_info=True) |
| 15 |