@contextlib.contextmanager
def capture_output(stream, loglevel=None):
 root_logger = logging.getLogger()
 old_level = root_logger.getEffectiveLevel()
 old_id = getattr(local_context, u'session_id', None)
 local_context.session_id = (old_id or uuid.uuid4())
 old_output = getattr(local_context, u'output', None)
 old_loglevel = getattr(local_context, u'loglevel', None)
 streamhandler = logging.StreamHandler(stream)
 streamhandler.setFormatter(FlexGetFormatter())
 streamhandler.addFilter(SessionFilter(local_context.session_id))
 if (loglevel is not None):
  loglevel = get_level_no(loglevel)
  streamhandler.setLevel(loglevel)
  if (not root_logger.isEnabledFor(loglevel)):
   root_logger.setLevel(loglevel)
 local_context.output = stream
 local_context.loglevel = loglevel
 root_logger.addHandler(streamhandler)
 try:
  (yield)
 finally:
  root_logger.removeHandler(streamhandler)
  root_logger.setLevel(old_level)
  local_context.session_id = old_id
  local_context.output = old_output
  local_context.loglevel = old_loglevel

@ contextlib . contextmanager def capture_output ( stream , loglevel = None ) : root_logger = logging . getLogger ( ) old_level = root_logger . getEffectiveLevel ( ) old_id = getattr ( local_context , u'session_id' , None ) local_context . session_id = ( old_id or uuid . uuid4 ( ) ) old_output = getattr ( local_context , u'output' , None ) old_loglevel = getattr ( local_context , u'loglevel' , None ) streamhandler = logging . StreamHandler ( stream ) streamhandler . setFormatter ( FlexGetFormatter ( ) ) streamhandler . addFilter ( SessionFilter ( local_context . session_id ) ) if ( loglevel is not None ) : loglevel = get_level_no ( loglevel ) streamhandler . setLevel ( loglevel ) if ( not root_logger . isEnabledFor ( loglevel ) ) : root_logger . setLevel ( loglevel ) local_context . output = stream local_context . loglevel = loglevel root_logger . addHandler ( streamhandler ) try : ( yield ) finally : root_logger . removeHandler ( streamhandler ) root_logger . setLevel ( old_level ) local_context . session_id = old_id local_context . output = old_output local_context . loglevel = old_loglevel
context manager which captures all log and console output to given stream while in scope .