stream object that redirects writes to a logger instance.
| 26 | |
| 27 | |
| 28 | class StreamToLoguru: |
| 29 | """ |
| 30 | stream object that redirects writes to a logger instance. |
| 31 | """ |
| 32 | |
| 33 | def __init__(self, level="INFO", caller_names=("apex", "pycocotools")): |
| 34 | """ |
| 35 | Args: |
| 36 | level(str): log level string of loguru. Default value: "INFO". |
| 37 | caller_names(tuple): caller names of redirected module. |
| 38 | Default value: (apex, pycocotools). |
| 39 | """ |
| 40 | self.level = level |
| 41 | self.linebuf = "" |
| 42 | self.caller_names = caller_names |
| 43 | |
| 44 | def write(self, buf): |
| 45 | full_name = get_caller_name(depth=1) |
| 46 | module_name = full_name.rsplit(".", maxsplit=-1)[0] |
| 47 | if module_name in self.caller_names: |
| 48 | for line in buf.rstrip().splitlines(): |
| 49 | # use caller level log |
| 50 | logger.opt(depth=2).log(self.level, line.rstrip()) |
| 51 | else: |
| 52 | sys.__stdout__.write(buf) |
| 53 | |
| 54 | def flush(self): |
| 55 | pass |
| 56 | |
| 57 | |
| 58 | def redirect_sys_output(log_level="INFO"): |
no outgoing calls
no test coverage detected