storing logger messages in a string

后端 未结 4 928
佛祖请我去吃肉
佛祖请我去吃肉 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:51

    You can also write your own stream class. As https://docs.python.org/2/library/logging.handlers.html says, only writeand flushare used for the streaming.

    Example:

    import logging
    
    class LogStream(object):
        def __init__(self):
            self.logs = ''
    
        def write(self, str):
            self.logs += str
    
        def flush(self):
            pass
    
        def __str__(self):
            return self.logs
    
    log_stream = LogStream()
    logging.basicConfig(stream=log_stream, level=logging.DEBUG)
    
    log = logging.getLogger('test')
    log.debug('debugging something')
    log.info('informing user')
    
    print(log_stream)
    

    Outputs:

    DEBUG:test:debugging something
    INFO:test:informing user
    

提交回复
热议问题