Logging all uncaught exceptions

Steven D'Aprano steve at pearwood.info
Mon Jul 14 05:07:24 EDT 2014


On Mon, 14 Jul 2014 06:09:32 +0000, Steven D'Aprano wrote:

> I want to catch all uncaught exceptions in my application, log them,
> then handle as normal. Which, in practice, means a traceback. Is this
> the right way to do it?

I think I've answered my own question, which leads to the next question.

I'm logging with the syslog handler, and I can see all the logged 
messages *except* those generated by my logger's exception method.

Here's my code, consisting of two modules:


# === mylogging.py ===
import logging
import logging.handlers

name = 'Spam'
mylogger = logging.getLogger(name)
handler = logging.handlers.SysLogHandler(address='/dev/log')
mylogger.addHandler(handler)
mylogger.setLevel(logging.DEBUG)
mylogger.info('started logging ' + name)


# === main.py ===
from mylogging import mylogger
mylogger.info('main.py running')
mylogger.debug('I can see debugging messages too')

import sys
def my_error_handler(type, value, tb):
    msg = "Uncaught %s: %s" % (type, value)
    mylogger.exception(msg)
    sys.__excepthook__(type, value, tb)

# Install exception handler.
sys.excepthook = my_error_handler

mylogger.info('testing exception logging...')
raise RuntimeError('a fake error occurred')



I run it from the command line on a Debian squeeze system:

steve at runes:~/test_logging$ python2.6 main.py 
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    raise RuntimeError('a fake error occurred')
RuntimeError: a fake error occurred


The debug and info messages are logged:

root at runes:/var/log# tail -1 debug
Jul 14 19:04:39 runes I can see debugging messages too

root at runes:/var/log# tail -3 messages
Jul 14 19:04:39 runes started logging Spam
Jul 14 19:04:39 runes main.py running
Jul 14 19:04:39 runes testing exception logging...


but the exception info which should have been generated by 
mylogger.exception doesn't appear anywhere I can see.


What am I doing wrong?


-- 
Steven



More information about the Python-list mailing list