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