Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Best Way เพื่อ Log Python Exception

ใช้ logging.exception() ภายใน except block

ตัวอย่าง

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 "...", line 3, in 
    print('toy' + 6)
TypeError: cannot concatenate 'str' and 'int' objects

Python 3: ต้องเรียก logging.exception() ภายใน except block เท่านั้น ไม่งั้นจะได้ weird exception