I wanted to store all the intermediate log messages (warn, info, error) to a string in python and finally at the end of program, display everything as a report to the consol
Note that solutions involving basicConfig set attributes of the root logger which all other loggers inherit from, this can be unwanted because libraries will also log to it. My use case is a website that calls a data processing module, and I only want to capture that module's logs specifically. This also has the advantage of allowing existing handlers that log to file and the terminal to persist:
import io, logging
from django.http import HttpResponse
log_stream = io.StringIO()
log_handler = logging.StreamHandler(log_stream)
logging.getLogger('algorithm.user_output').addHandler(log_handler)
algorithm()
return HttpResponse(f'{log_stream.getvalue()}')
In algorithm.py:
logger = logging.getLogger(__name__ + '.user_output') # 'algorithm.user_output'