My test harness already dumps the logging buffer on test failure.
What I need this for is debugging. My test harness verbose = 2 flag turns on logging globally, and I need to see the logging from the code under test correctly interspersed with the other logging (some of which comes from *other processes*...there are integration tests as well as unit tests).
Here's what I'm currently using:
@contextmanager
def assertLogs(self, logger=None, level=None):
cm = super().assertLogs(logger, level)
watcher = cm.__enter__()
if verbose > 1:
capture_handler = cm.logger.handlers
cm.logger.propagate = cm.old_propagate
cm.logger.handlers = cm.old_handlers + cm.logger.handlers
try:
yield watcher
finally:
if verbose > 1:
# Restore before exit to avoid a race. Otherwise debug output
# sometimes gets written to the console during non-v.
cm.logger.propagate = False
cm.logger.handlers = capture_handler
cm.__exit__(None, None, None)
So, I have a solution, and if my use case is too specialized I can just continue to use that solution, though I am forced to poke at the internals to make it work :)
I am also, by the way, depending on the fact that when the logging is being done by another thread I can "watch" cm.output until specific logging that I am expecting appears in the buffer. I'm sure that's going to make some people throw up their hands in disgust, considering among other things the fact that it involves a busy-wait, but while it may be a somewhat ugly hack, it is a hack that works well.
|