Skip to main content
 首页 » 编程设计

python之使用日志记录将消息记录到数组/列表

2025年05月04日34freeliver54

目前正在使用 python 日志记录将消息记录到日志文件和控制台(如果 --verbose)。

如何配置日志记录以将消息也记录到数组/列表中?

请您参考如下方法:

  1. 发帖后想通了。
  2. 将流用于字符串。
  3. 这是代码片段,不包括标准输出流和普通记录器文件句柄:

    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()