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

执行时(在 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. 我怎样才能只获得引发异常的文件的基本名称(名称+扩展名),而不是带有目录的全名?

总结一下:我想输出到日志文件,如下所示:

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

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

4

1 回答 1

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)))
于 2017-10-14T14:36:23.013 回答