@contextmanager<EOL>def catching_logs(handler, formatter=None, level=None):
root_logger = logging.getLogger()<EOL>if formatter is not None:<EOL><INDENT>handler.setFormatter(formatter)<EOL><DEDENT>if level is not None:<EOL><INDENT>handler.setLevel(level)<EOL><DEDENT>add_new_handler = handler not in root_logger.handlers<EOL>if add_new_handler:<EOL><INDENT>root_logger.addHandler(handler)<EOL><DEDENT>if level is not None:<EOL><INDENT>orig_level = root_logger.level<EOL>root_logger.setLevel(min(orig_level, level))<EOL><DEDENT>try:<EOL><INDENT>yield handler<EOL><DEDENT>finally:<EOL><INDENT>if level is not None:<EOL><INDENT>root_logger.setLevel(orig_level)<EOL><DEDENT>if add_new_handler:<EOL><INDENT>root_logger.removeHandler(handler)<EOL><DEDENT><DEDENT>
Context manager that prepares the whole logging machinery properly.