Fake file-like stream object that redirects writes to a logger instance.
| 64 | |
| 65 | |
| 66 | class StreamToLogger(object): |
| 67 | """ |
| 68 | Fake file-like stream object that redirects writes to a logger instance. |
| 69 | """ |
| 70 | |
| 71 | def __init__(self, logger, log_level=logging.INFO): |
| 72 | self.terminal = sys.stdout |
| 73 | self.logger = logger |
| 74 | self.log_level = log_level |
| 75 | self.linebuf = '' |
| 76 | |
| 77 | def __getattr__(self, attr): |
| 78 | return getattr(self.terminal, attr) |
| 79 | |
| 80 | def write(self, buf): |
| 81 | temp_linebuf = self.linebuf + buf |
| 82 | self.linebuf = '' |
| 83 | for line in temp_linebuf.splitlines(True): |
| 84 | # From the io.TextIOWrapper docs: |
| 85 | # On output, if newline is None, any '\n' characters written |
| 86 | # are translated to the system default line separator. |
| 87 | # By default sys.stdout.write() expects '\n' newlines and then |
| 88 | # translates them so this is still cross platform. |
| 89 | if line[-1] == '\n': |
| 90 | self.logger.log(self.log_level, line.rstrip()) |
| 91 | else: |
| 92 | self.linebuf += line |
| 93 | |
| 94 | def flush(self): |
| 95 | if self.linebuf != '': |
| 96 | self.logger.log(self.log_level, self.linebuf.rstrip()) |
| 97 | self.linebuf = '' |
| 98 | |
| 99 | |
| 100 | def violates_moderation(text): |