猴子补丁的应用,猴子补丁来改变日志。

Posted ydf0509

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了猴子补丁的应用,猴子补丁来改变日志。相关的知识,希望对你有一定的参考价值。

打这个猴子补丁,就可以不需要修改任何一处代码,就能使项目中所有py文件的所有控制台日志变彩色和可点击跳转。

 

import logging


class ColorHandler(logging.Handler):
    """
    A handler class which writes logging records, appropriately formatted,
    to a stream. Note that this class does not close the stream, as
    sys.stdout or sys.stderr may be used.
    """

    terminator = \\n
    bule = 96 if os.name == nt else 36
    yellow = 93 if os.name == nt else 33

    def __init__(self, stream=None,):
        """
        Initialize the handler.

        If stream is not specified, sys.stderr is used.
        """
        logging.Handler.__init__(self)
        self.formatter = logging.Formatter(
            %(asctime)s - %(name)s - "%(pathname)s:%(lineno)d" - %(funcName)s - %(levelname)s - %(message)s,
            "%Y-%m-%d %H:%M:%S")
        if stream is None:
            stream = sys.stdout  # stderr无彩。
        self.stream = stream



    def flush(self):
        """
        Flushes the stream.
        """
        self.acquire()
        try:
            if self.stream and hasattr(self.stream, "flush"):
                self.stream.flush()
        finally:
            self.release()

    def emit(self, record):
        """
        Emit a record.

        If a formatter is specified, it is used to format the record.
        The record is then written to the stream with a trailing newline.  If
        exception information is present, it is formatted using
        traceback.print_exception and appended to the stream.  If the stream
        has an ‘encoding‘ attribute, it is used to determine how to do the
        output to the stream.
        """
        # noinspection PyBroadException
        try:
            msg = self.format(record)
            stream = self.stream
            if record.levelno == 10:
                # msg_color = (‘\\033[0;32m%s\\033[0m‘ % msg)  # 绿色
                msg_color = (\\033[0;%sm%s\\033[0m % (32 , msg))  # 绿色
            elif record.levelno == 20:
                msg_color = (\\033[0;%sm%s\\033[0m % (self.bule, msg))  # 青蓝色 36    96
            elif record.levelno == 30:
                msg_color = (\\033[0;%sm%s\\033[0m % (self.yellow, msg))
            elif record.levelno == 40:
                msg_color = (\\033[0;35m%s\\033[0m % msg)  # 紫红色
            elif record.levelno == 50:
                msg_color = (\\033[0;31m%s\\033[0m % msg)  # 血红色
            else:
                msg_color = msg
            # print(msg_color,‘***************‘)
            stream.write(msg_color)
            stream.write(self.terminator)
            self.flush()
        except Exception:
            self.handleError(record)

    def __repr__(self):
        level = logging.getLevelName(self.level)
        name = getattr(self.stream, name, ‘‘)
        if name:
            name +=  
        return <%s %s(%s)> % (self.__class__.__name__, name, level)


logging.StreamHandler = ColorHandler   # 这里就是打猴子补丁
from logging import StreamHandler

logger = logging.getLogger(abc)
print(logger.handlers)
print(StreamHandler().formatter)
logger.addHandler(StreamHandler())
logger.setLevel(10)

def my_func():
    logger.debug(11111111111111)
    logger.info(22222222222222)
    logger.warning(33333333333)
    logger.error(4444444444444)
    logger.critical(555555555555)
    print(logger.handlers)

if __name__ == __main__:
    my_func()

 

 

原来

技术图片

 

 

 打狗子补丁后,也就是执行下面这句话,就能使日志变彩色和可跳转。

logging.StreamHandler = ColorHandler

技术图片

 

以上是关于猴子补丁的应用,猴子补丁来改变日志。的主要内容,如果未能解决你的问题,请参考以下文章

Ruby 中的“猴子补丁”到底是啥意思?

寻找可能导致麻烦的 Ruby 猴子补丁的来源?

猴子补丁 Python 类

用于 PySpark 的酸洗猴子补丁 Keras 模型

Python面试题之“猴子补丁”(monkey patching)指的是什么?这种做法好吗?

gevent猴子补丁和断点