python - 在日志输出中禁止异常上下文

时间:2017-10-13 20:40:58

标签: python exceptionhandler

我有以下测试代码:

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

我有一个双重问题:

  1. 有没有办法抑制异常上下文并只获取 最后的追溯?

  2. 我怎么才能得到文件的基名(name + extension)     引发异常,而不是目录的全名?

  3. 总结一下:我想输出日志文件:

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

    提前感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分: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)))