Skip to content

Instantly share code, notes, and snippets.

@66Ton99
Created August 28, 2015 16:26
Show Gist options
  • Save 66Ton99/b13c2867adef506554a4 to your computer and use it in GitHub Desktop.
Save 66Ton99/b13c2867adef506554a4 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())
@66Ton99
Copy link
Author

66Ton99 commented Aug 28, 2015

@sapana-sainee30
Copy link

Hi This last print(log_contents.lower()) statement doesn't print anything, can you help

@prabhuSub
Copy link

Hi This last print(log_contents.lower()) statement doesn't print anything, can you help

Mostly your contents to the logger are None! You should check if the logger has contents to it.

@prabhuSub
Copy link

CC http://alanwsmith.com/capturing-python-log-output-in-a-variable but with little improvement

Thanks a lot! Helps a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment