问题
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:
- Figured this out after posting.
- Used a Stream to a string.
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