[Python-Dev] logging exceptions

Jeremy Hylton jeremy at alum.mit.edu
Wed Feb 18 14:54:53 EST 2004


Zope 2.7 is using the logging package internally as the implementation
for its old zLOG API.  We've run into one problem, probably caused by
carelessness on our part.  

zLOG allows you to pass exc_info to be logged, but logging only allows
you to specify a flag saying whether the current exception should be
logged.  (I recall that this was discussed at length, but not why the
current solution was reached.)  There are several call sites that depend
on this feature to capture an exception, try to recover gracefully or
log a traceback if recovery is impossible.  So we depend on this
feature, but can't get it out of logging very easily.

We've come up with this as a work-around:

prev = sys.exc_info()
if prev != exc_info:
    try:
        raise exc_info[0], exc_info[1], exc_info[2]
    except:
        pass
else:
    prev = None
logging.error(..., exc_info=1)
if prev is not None:
    try:
        raise prev[0], prev[1], prev[2]
    except:
        pass

This seems like a pretty gross way to set and restore the current
exception, but it would work.  Would it be possible to add a feature to
logging to allow us to specify the traceback directly?  The only reason
we need to set the current exception is this code in logging:

    def _log(self, level, msg, args, exc_info=None):
        # ...
        if exc_info:
            exc_info = sys.exc_info()
        record = self.makeRecord(self.name, level, fn, lno, msg, args,
exc_info)
        self.handle(record)

I suppose another option is to create a Logger subclass with a different
_log() method.

Jeremy





More information about the Python-Dev mailing list