New submission from James Lekas <[email protected]>:
logging.Formatter.format() creates a cache called exc_text with a copy of the
traceback text which it uses for all log handlers (I think). When this cache
is set, format() does not call formatException to format the
exception/traceback data.
Unfortunately, this means that one cannot override
logging.Formatter.formatException() for a specific log Handler. For example,
to create a stripped-down exception message for emailing to a non-technical
audience, one might create the derived class NoStaceTraceFormatter, and attach
an instance to the SMTPHandler using setFormatter():
class NoStackTraceFormatter(logging.Formatter):
def formatException(self, exc_info): # Don't emit the stack trace
return '\n'.join(traceback.format_exception_only(exc_info[0],
exc_info[1])) # type and value only
At least when other handlers exist for the logger, the new formatException call
will probably never be invoked. (This might depend on the order in which the
handlers are called when an exception log message arrives: the first handler
would define the exception text.)
One partial workaround is to override the logging.Formatter.format() method to
defeat the cache, causing the overriding formatException to be called.
def format(self, record):
record.exc_text = None # Defeat the common cache so formatException
will be called.
return logging.Formatter.format(self, record)
Unfortunately, this will create a new cached copy of the special-purpose
exception text, possibly causing downstream handlers to emit the wrong message.
A possible solution would be to move the caching from
logging.Formatter.format() to logging.Formatter.formatException, which would at
least allow an individual handler to ignore the cache. (However, all handlers
would share the cache, possibly leading to trouble.)
The cache should probably be eliminated, as the premise on which it is based,
"it's constant anyway", isn't strictly true.
----------
components: Library (Lib)
messages: 153425
nosy: jimlekas
priority: normal
severity: normal
status: open
title: logging.Formatter Cache Prevents Exception Format Overriding
type: behavior
versions: Python 2.7
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue14024>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com