Last active
July 25, 2018 09:34
-
-
Save lotusirous/5b2ed5b508c645b4e5d2ea868f0724d4 to your computer and use it in GitHub Desktop.
Python wrap stdout for logging purpose. However, this method is not support to write or read binary data from/to the standard streams.
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 | |
| import sys | |
| # Setup logger | |
| logger = logging.getLogger(__name__) | |
| logger.setLevel(logging.DEBUG) | |
| handler = logging.FileHandler("./out.log") | |
| formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
| handler.setLevel(logging.DEBUG) | |
| handler.setFormatter(formatter) | |
| logger.addHandler(handler) | |
| class StdWrapper(object): | |
| def __init__(self, logger, std): | |
| self.old_std = std | |
| self.logger = logger or logging.getLogger() | |
| def write(self, *arg, **kwargs): | |
| if '\n' not in arg and ' ' != arg[-1]: # beautiful output | |
| msg = ''.join(map(str, arg)).replace('\n', "") | |
| logger.info(msg) | |
| self.old_std.write(*arg) | |
| def flush(self): | |
| self.old_std.flush() | |
| wrap_stdout = StdWrapper(logger, sys.stdout) | |
| sys.stdout = wrap_stdout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment