python中的traceback模塊被用于跟蹤異常返回信息,可以在logging中記錄下traceback。
traceback.format_exc()獲取異常為字符串,保存到日志文件
try:
importlxml
except:
trace=traceback.format_exc()
logger.error(f'\n{trace}')
日志文件輸出:
Traceback(mostrecentcalllast):
File"/home/ldy/myself/untitled/scripts/scripts.py",line20,in
importlxml
ModuleNotFoundError:Nomodulenamed'lxml'
與traceback.print_exc()的區(qū)別是,后者直接輸出在控制臺(tái)。
以上內(nèi)容為大家介紹了python培訓(xùn)之如何錯(cuò)誤追蹤,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。