Support for testing logging code

If you want to test that your code generates proper log output, you can create and install a handler that collects output using zope.testing.loggingsupport:

>>> from zope.testing.loggingsupport import InstalledHandler
>>> handler = InstalledHandler('')

The handler is installed into loggers for all of the names passed. In addition, the logger level is set to 1, which means, log everything. If you want to log less than everything, you can provide a level keyword argument. The level setting effects only the named loggers.

>>> import logging
>>> handler_with_levels = InstalledHandler('baz', level=logging.WARNING)

Then, any log output is collected in the handler:

>>> logging.getLogger('').exception('eek')
>>> logging.getLogger('').info('blah blah')
>>> for record in handler.records:
...     print_(, record.levelname)
...     print_(' ', record.getMessage()) ERROR
  eek INFO
  blah blah

A similar effect can be gotten by just printing the handler:

>>> print_(handler) ERROR
  eek INFO
  blah blah

After checking the log output, you need to uninstall the handler:

>>> handler.uninstall()
>>> handler_with_levels.uninstall()

At which point, the handler won’t get any more log output. Let’s clear the handler:

>>> handler.clear()
>>> handler.records

And then log something:

>>> logging.getLogger('').info('blah')

and, sure enough, we still have no output:

>>> handler.records