log messages to an array/list with logging

冷暖自知 提交于 2021-01-28 10:31:43

问题


Currently am using python logging to log messages to a log file and to console (if --verbose).

How can I configure logging to also record messages into an array/list?


回答1:


  1. Figured this out after posting.
  2. Used a Stream to a string.
  3. Here is snippet of the code, not including the stdout Stream and the normal logger file handle:

    import io
    import logging
    
    logger = logging.getLogger()
    errors = io.StringIO()
    formatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s() - %(levelname)s - %(message)s',"%Y-%m-%d %H:%M:%S")
    eh = logging.StreamHandler(errors)
    eh.setFormatter(formatter)
    logger.addHandler(eh)
    
    logger.error("This is a test error message")
    contents=errors.getvalue()
    print("error string=>{}".format(contents))
    errors.close()
    


来源:https://stackoverflow.com/questions/31364346/log-messages-to-an-array-list-with-logging

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!