import logging import sys class ConsoleHandler(logging.Handler): terminator = ‘\n‘ def __init__(self, level=logging.NOTSET): super().__init__(level) def _flush(self, stream): self.acquire() try: if stream and hasattr(stream, ‘flush‘): stream.flush() finally: self.release() def emit(self, record): try: msg = self.format(record) stream = sys.stderr if record.levelname == ‘ERROR‘else sys.stdout stream.write(msg) stream.write(self.terminator) self._flush(stream) except BaseException as ex: record.msg = record.getMessage() + ‘ WriteLogException:‘ + str(ex) self.handleError(record) if __name__ == "__main__": _logger = logging.root _logger.setLevel(logging.INFO) formatter = logging.Formatter(‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘) _console_handler = ConsoleHandler(logging.INFO) _console_handler.setFormatter(formatter) _logger.addHandler(_console_handler) logging.info(‘info‘) logging.error(‘error‘)
原文地址:https://www.cnblogs.com/stones/p/8340864.html
时间: 2024-10-11 13:04:41