打这个猴子补丁,就可以不需要修改任何一处代码,就能使项目中所有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
原文地址:https://www.cnblogs.com/ydf0509/p/11221043.html
时间: 2024-11-05 20:33:21