Created
March 30, 2019 13:35
-
-
Save Fak3/29532386348aea9f47054148bdecefa7 to your computer and use it in GitHub Desktop.
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
def streamdup(stream, filename, mode='a+'): | |
""" | |
Aka "tee". | |
Duplicate stream output to the file with given name. | |
Usage: | |
>>> streamcopy(sys.stderr, 'myfile', 'a+') | |
""" | |
stream._tee = open(filename, mode) | |
def write(*a): TextIOWrapper.write(stream, *a); stream._tee.write(*a) | |
stream.write = write | |
#import logging | |
#LOGFORMAT = '%(levelname)s %(asctime)s %(module)s.py: %(message)s' | |
#def add_log_handler(handler): | |
#handler.setFormatter(logging.Formatter(LOGFORMAT)) | |
#logging.getLogger().addHandler(handler) | |
class TeeLogger(logging.LoggerAdapter): | |
""" | |
This logger will log messages to the file and pass on to the other | |
logger which it is attached to. | |
""" | |
def __init__(self, filename, logger=None): | |
""" | |
param `logger`: the logger instance which this logger will be attached to. | |
default is the root logger. | |
""" | |
self.logger = logger or logging.getLogger() | |
_filehandler = logging.FileHandler(filename) | |
_filehandler.setFormatter(self.logger.handlers[0].formatter) | |
self.filelogger = logging.Logger(id(filename), level=self.logger.level) | |
self.filelogger.addHandler(_filehandler) | |
def log(self, level, msg, *args, **kwargs): | |
if self.isEnabledFor(level): | |
self.logger.log(level, msg, *args, **kwargs) | |
self.filelogger.log(level, msg, *args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment