[英]python - suppress exception context in log output
我有以下測試代碼:
import logging
def main():
l = ['a', 'b']
l.index('c')
logging.basicConfig(level=logging.DEBUG, filename='myapp.log', format='')
try:
main()
except:
logging.exception('')
執行時(在Windows 7下的Python 2.7.10中),它將以下跟蹤信息輸出到日志文件:
Traceback (most recent call last):
File "C:/Documents and Settings/maurobio/test/log.py", line 12, in <module>
main()
File "C:/Documents and Settings/maurobio/test/log.py", line 6, in main
l.index('c')
ValueError: 'c' is not in list
我有一個雙重問題:
有沒有辦法抑制異常上下文並僅獲取最后的回溯?
我如何只獲取引發異常的文件的基本名稱(名稱和擴展名),而不是帶有目錄的全名?
總結:我想輸出到日志文件,就像:
Traceback (most recent call last):
File "log.py", line 6, in main
l.index('c')
ValueError: 'c' is not in list
在此先感謝您提供的任何幫助。
這是我最終實現的解決方案。 希望它對其他人也有幫助。
import os
import sys
import logging
import traceback
def main():
l = ['a', 'b']
l.index('c')
logging.basicConfig(level=logging.DEBUG, filename='myapp.log', filemode='w', format='')
try:
main()
except Exception, e:
eclass, e, etrace = sys.exc_info()
efile, eline, efunc, esource = traceback.extract_tb(etrace)[-1]
logging.error('Traceback (most recent call last):')
logging.error(' File "%s", line %d in %s\n%s: %s' % (os.path.basename(efile), eline, efunc, eclass.__name__, str(e)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.