storing logger messages in a string

后端 未结 4 958
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 10:00

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

4条回答
  •  再見小時候
    2021-01-02 10:37

    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'
    

提交回复
热议问题