码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-24 12:41:59      阅读:778      评论:0      收藏:0      [点我收藏+]

标签:etl   sage   控制   __name__   erro   logger   post   write   imp   

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 == ERRORelse 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)

 

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

标签:etl   sage   控制   __name__   erro   logger   post   write   imp   

原文地址:https://www.cnblogs.com/stones/p/8340864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!