0

I have the following test code:

import logging

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

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

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

When executed (in Python 2.7.10 under Windows 7), it outputs to the log file the following traceback info:

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

I have a twofold question:

  1. Is there a way to suppress the exception context and get only the last traceback?

  2. How could I get only the basename (name + extension) of the file raising the exception, instead of the full name with directory?

To sum up: I would like to output to the log file just something like:

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

Thanks in advance for any assistance you can provide.

maurobio
  • 1,480
  • 4
  • 27
  • 38
  • Why don't you try to capture the exception information using `sys.exc_info()` and `traceback.format_tb(sys.exc_info()[2])` to create a formatted message to be logged. – Payman Oct 14 '17 at 00:17
  • Will investigate this, thanks for the suggestions. – maurobio Oct 14 '17 at 00:27

1 Answers1

0

Here is the solution I finally achieved. Hope it can be also helpful to others.

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)))
maurobio
  • 1,480
  • 4
  • 27
  • 38