4

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
  • Been working on this for many hours, after posting this question I just figured it out after 30 minutes or so Commented Jul 12, 2015 at 5:00

1 Answer 1

10
  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()
    
Sign up to request clarification or add additional context in comments.

1 Comment

I get 'TypeError: can't write str to text stream' with python 2.6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.