2017-10-13 85 views
0

我有以下的測試代碼:蟒蛇 - 在日誌輸出抑制異常情況下

import logging 

def main(): 
    l = ['a', 'b'] 
    l.index('c') 

logging.basicConfig(level=logging.DEBUG, filename='myapp.log', format='') 

try: 
    main() 
except: 
    logging.exception('') 

當(在Python 2.7.10在Windows 7下)執行,其輸出到日誌文件以下回溯信息:

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 

我有一個雙重的問題:

  1. 有沒有辦法來抑制異常情況下,只得到ŧ他 最後一個回溯?

  2. 如何才能獲得文件 的基名(名稱+擴展名),而不是帶目錄的全名?

綜上所述:我想輸出到日誌文件只是這樣的:

Traceback (most recent call last): 
    File "log.py", line 6, in main 
    l.index('c') 
ValueError: 'c' is not in list 

預先感謝您可以提供任何幫助。

+0

你爲什麼不嘗試使用'sys.exc_info()'和'traceback.format_tb(sys.exc_info()[2])'創建要記錄一個格式化的信息來捕獲異常信息。 – Payman

+0

將對此進行調查,感謝您的建議。 – maurobio

回答

0

這是我終於實現的解決方案。希望它對其他人也有幫助。

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)))