Skip to content

Instantly share code, notes, and snippets.

@liuyigh
Forked from 66Ton99/logging_to_str.py
Created February 21, 2019 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuyigh/c80e136564f61b0bb1e0491f7188b3b8 to your computer and use it in GitHub Desktop.
Save liuyigh/c80e136564f61b0bb1e0491f7188b3b8 to your computer and use it in GitHub Desktop.
Capturing Python Log Output In A Variable
import logging
from StringIO import StringIO as StringBuffer
logger = logging.getLogger('basic_logger')
logger.setLevel(logging.DEBUG)
### Setup the console handler with a StringIO object
log_capture_string = StringBuffer()
# log_capture_string.encoding = 'cp1251'
ch = logging.StreamHandler(log_capture_string)
ch.setLevel(logging.DEBUG)
### Optionally add a formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
### Add the console handler to the logger
logger.addHandler(ch)
### Send log messages.
logger.debug('debug message')
logger.info('info message')
logger.warn(u'warn message')
logger.error('error message')
logger.critical(u'critical message')
### Pull the contents back into a string and close the stream
log_contents = log_capture_string.getvalue()
log_capture_string.close()
### Output as lower case to prove it worked.
print(log_contents.lower())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment