The following is a example that installs a handler to capture the logs.
This works in Python 2.7. For Python 3 replace cStringIO.StringIO
with io.StringIO
or io.BytesIO
. Or use the ListHander
that does not need either.
If you would rather keep the log records before they are formatted or the separation between the lines for each message. This can be adapted but requires writing a Handler
.
import logging
import cStringIO
class Handler(object):
def __init__(self, handler):
self.handler = handler
def __enter__(self):
logging.root.handlers.append(self.handler)
return self.handler
def __exit__(self, type, value, tb):
logging.root.handlers.remove(self.handler)
def print_logs():
logging.info('info log 1.')
logging.warning('warning log 1.')
logging.error('error log 1.')
logging.error('error log 2.')
h = logging.StreamHandler(stream=cStringIO.StringIO())
h.setLevel('ERROR')
with Handler(h):
print_logs()
error_logs = h.stream.getvalue().splitlines()
error_logs
class RecordListHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
self.log = []
def emit(self, record):
self.log.append(record)
class ListHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
self.log = []
def emit(self, record):
msg = self.format(record)
self.log.append(msg)
h = RecordListHandler()
h.setLevel('ERROR')
with Handler(h):
print_logs()
error_logs = h.log
error_logs
h = ListHandler()
h.setLevel('ERROR')
with Handler(h):
print_logs()
error_logs = h.log
error_logs