Created
February 25, 2014 07:55
-
-
Save mindw/9204716 to your computer and use it in GitHub Desktop.
redirecting std out/err into files
This file contains hidden or 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 | |
| logging.basicConfig(filename='example.log',filemode="w", level=logging.DEBUG) | |
| import sys | |
| class StreamToLogger(object): | |
| """ | |
| Fake file-like stream object that redirects writes to a logger instance. | |
| """ | |
| def __init__(self, logger, log_level=logging.INFO): | |
| self.logger = logger | |
| self.log_level = log_level | |
| self.linebuf = '' | |
| def write(self, buf): | |
| for line in buf.rstrip().splitlines(): | |
| self.logger.log(self.log_level, line.rstrip()) | |
| logging.basicConfig( | |
| level=logging.DEBUG, | |
| format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', | |
| filename="out.log", | |
| filemode='a' | |
| ) | |
| stdout_logger = logging.getLogger('STDOUT') | |
| sl = StreamToLogger(stdout_logger, logging.DEBUG) | |
| sys.stdout = sl | |
| stderr_logger = logging.getLogger('STDERR') | |
| sl = StreamToLogger(stderr_logger, logging.DEBUG) | |
| sys.stderr = sl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment