Welcome, guest | Sign In | My Account | Store | Cart

If you want to log exceptions, here is a simple way to do so without having to explicitly repetitiously call the logger in each try-except clause.

Python, 28 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import logging

# adjust config to your own preferences
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='myapp.log',
                    filemode='w')

class LoggingException(Exception):
    logger = logging.getLogger()
    logLevel = logging.ERROR

    def __init__(self):
        self.logger.log(self.logLevel, self.logMessage())

    def logMessage(self):
        return 'Exception occured'


if __name__ == '__main__':
    class BlewIt(LoggingException):
        logLevel = logging.WARNING
        def logMessage(self):
            return 'you blew it'
    try:
        raise BlewIt
    except:
        pass

In any somewhat complex application, you likely want to log and handle most exceptions. The recipe shows a way to separate logging from handling, so that it is not necessary to explicitly invoke the logging mechanism in each try-except clause. This recipe is intended just as an illustration of the general idea. In real life, you probably want to have .logMessage produce some more informative logging messages than shown in the example. The place to get information about the specifics of the exception is module traceback. Also, module logging is a somewhat complex animal. You have lots of options there for directing and formatting your log info, but of course you may want to choose a different and simpler logging mechanism altogether.

1 comment

Miguel Garcia 13 years, 7 months ago  # | flag

This is great. However, it makes me wander: how should I do it if I want to capture ANY exceptions, included those built-in in Python such as ZeroDivisionError, etc?