A library I'm using takes a function like this:
@contextlib.contextmanager
def stdout_cm():
yield sys.stdout
Now rather than foo(stdout_cm)
, how do I send through a logging
instance that tee
s to multiple handlers? (stdout and StringIO)
Attempt:
from sys import stdout, stderr
from cStringIO import StringIO
from logging import getLogger, basicConfig, StreamHandler
from subprocess import check_call
basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M', level='INFO')
log = getLogger(__name__)
console = StreamHandler(StringIO())
log.addHandler(console)
log.addHandler(StreamHandler(stdout))
class LoggerContext(object):
def __init__(self, logger, level=None, close=True):
self.logger = logger
self.level = level
self.close = close
def __call__(self):
return self
def __enter__(self):
if self.level is not None:
self.old_level = self.logger.level
self.logger.setLevel(self.level)
def __exit__(self, et, ev, tb):
if not self.close:
return
for handler in self.logger.handlers:
handler.close()
Simplified function:
def foo(f):
with f() as fh:
check_call(["printf '\n\n' | wc -l"], shell=True, stderr=fh, stdout=fh)
foo(LoggerContext(log)) #, level='WARN')
print console.stream.getvalue()
Prelude:
Class (based on https://stackoverflow.com/a/4838875):
Usage: