Python3.5 控制台日志输出,区分标准输出与错误输出

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')

 

posted @ 2018-01-24 11:40  stone_wl  阅读(444)  评论(0编辑  收藏  举报