'How to log all exceptions in python 3

There are a lot of exception I don't want to catch, I want them to stop processing, but, I still want the stack trace in the log file. Is there a way to setup a logger so that it automatically logs all exceptions?

Right now I am writing things like this a lot:

try:
  blah
except:
  logging.exception('doing blah')
  raise

which take up a lot of time and space + it'll only log the exceptions for which I have a try clause for, not the other ones.

Thanks.



Solution 1:[1]

You could put a catch all handler at the topmost level of your code:

try:
  everything
except:
  logging.exception('unhandled')
  raise

Solution 2:[2]

'sys.exc_info()' helped with 'text' from most common exceptions viz., (1)'NameError'; (2) 'FileNotFoundError';(3)'ZeroDivisionError' and (4)'IndexError':...may be more too #============================================

import sys
try:  
    #<Anything here>
except:
    print(str(sys.exc_info()))

#============================================ Example:

import sys
try:
    #Unprompt one at atime
    z = (9/0)#ZeroDivisionError
    #f = open("I:\Invalidpath\inventory2.txt", "r")#FileNotFoundError
    #f = open("I:\validpath\inventory2.txt", r)#NameError
    #==========
    #a = [1, 2, 3]
    #print("Second element = %d" % (a[5]))#'IndexError'
    #==========
except:
    print(str(sys.exc_info()))

#==============================================

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jfs
Solution 2 Srini_N