2017-10-13 86 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)))