目前正在使用 python 日志记录将消息记录到日志文件和控制台(如果 --verbose)。
如何配置日志记录以将消息也记录到数组/列表中?
请您参考如下方法:
- 发帖后想通了。
- 将流用于字符串。
这是代码片段,不包括标准输出流和普通记录器文件句柄:
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()
