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