Created
August 28, 2015 16:26
-
-
Save 66Ton99/b13c2867adef506554a4 to your computer and use it in GitHub Desktop.
Capturing Python Log Output In A Variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
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.
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
Hi This last print(log_contents.lower()) statement doesn't print anything, can you help