Strange logging.Formatter behaviour

Tiaburn Stedd aleksandrs.zdancuks at gmail.com
Tue Nov 22 10:19:59 EST 2011


Hello, all!

I'm working on specific project and have a curious task where I need
to use specific formatter and custom handlers, which are switchable to
default handlers. Problem is that default handlers behaviour is to
consume errors, so errors raised from code have printed tracebacks,
but not passed outside logger, because of it silent behaviour.

Unit test for this is below:

import logging
import unittest

class SpecificFormatException(Exception):
    pass

class MyClass(object):
    def __init__(self, record):
       raise TypeError

class MyFormatter(logging.Formatter, object):
    def format(self, record):
        try:
            specific_format_record = MyClass(record)
        except TypeError:
            raise SpecificFormatException("Error raised")

class TestLogger(unittest.TestCase):
    def test_my_logger(self):
        self.logger = logging.getLogger(self.__class__.__name__)
        handler = logging.FileHandler('test_logger.log')
        handler.setFormatter(fmt=MyFormatter())
        self.logger.addHandler(handler)
        self.assertRaises(SpecificFormatException,
self.logger.warn,"Log something")

if __name__ == '__main__':
    unittest.main()


I don't believe this behavior is normal. I expect error raised in a
Formatter.format function, should be passed all the way up, but not
consumed.

I found a workaround:

class CustomFileHandler(logging.FileHandler, object):
    def handleError(self, record):
         super(CustomFileHandler, self).handleError(record)
         raise

But it looks ugly to add Custom*Handler for any default Handler (like,
StreamHandler, etc) to make them possible to fall out on any error.

There are raiseException switch in source of logging/__init__.py

  92 #raiseExceptions is used to see if exceptions during handling
should be
  93 #propagated
  94 #
  95 raiseExceptions = 1

But all it switch is only is traceback printed or not. I think this
behaviour is against Zen of Python: "Errors should never pass
silently."

May be logging library should be updated to contain 2 flags:
printTracebacks and raiseExceptions ?



More information about the Python-list mailing list