Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log messages to an array/list with logging

Tags:

python

logging

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?

like image 416
Fragtzack Avatar asked Oct 24 '25 04:10

Fragtzack


1 Answers

  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()
    
like image 190
Fragtzack Avatar answered Oct 27 '25 00:10

Fragtzack