【问题标题】:How to write colored text in log file with python如何使用python在日志文件中写入彩色文本
【发布时间】:2014-03-05 07:15:27
【问题描述】:

我有一个名为 LogFile.log 的日志文件 我使用写入文件的方式在这个文件中写入不同的日志:

logfile = open(LogFile.log, 'a')
logFile.write("<< INFO >> ")

我怎样才能用不同的颜色写我的日志(例如红色表示错误,绿色表示信息,橙色表示调试)?

我正在使用 Python 2.5,因为它与我正在使用的另一个工具完全兼容。

【问题讨论】:

    标签: python logging


    【解决方案1】:

    您可以使用 ANSI 颜色代码将彩色线条写入终端(请参阅Printing to STDOUT and log file while removing ANSI color codes),但不能将彩色线条写入文件。

    【讨论】:

      【解决方案2】:

      如果我错了,请纠正我,但我认为您不能将彩色消息输出到 utf-8 日志文件。

      如前所述,您可以使用彩色 CLI 或尝试实现自己的记录器,例如将日志消息输出到 html。 html就能实现着色。

      【讨论】:

      • 这是对先前答案的改写,但未提供更多信息。将来,如果您想对现有答案发表评论,请改为这样做。
      【解决方案3】:

      您可以将颜色与 python 日志模块集成

      BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
      
      #The background is set with 40 plus the number of the color, and the foreground with 30
      
      #These are the sequences need to get colored ouput
      RESET_SEQ = "\033[0m"
      COLOR_SEQ = "\033[1;%dm"
      BOLD_SEQ = "\033[1m"
      
      def formatter_message(message, use_color = True):
          if use_color:
              message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
          else:
              message = message.replace("$RESET", "").replace("$BOLD", "")
          return message
      
      COLORS = {
          'WARNING': YELLOW,
          'INFO': WHITE,
          'DEBUG': BLUE,
          'CRITICAL': YELLOW,
          'ERROR': RED
      }
      
      class ColoredFormatter(logging.Formatter):
          def __init__(self, msg, use_color = True):
              logging.Formatter.__init__(self, msg)
              self.use_color = use_color
      
          def format(self, record):
              levelname = record.levelname
              if self.use_color and levelname in COLORS:
                  levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
                  record.levelname = levelname_color
              return logging.Formatter.format(self, record)
      

      如果你想使用这个东西,那就创建你自己的记录器

      # Custom logger class with multiple destinations
      class ColoredLogger(logging.Logger):
          FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s]  %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
          COLOR_FORMAT = formatter_message(FORMAT, True)
          def __init__(self, name):
              logging.Logger.__init__(self, name, logging.DEBUG)                
      
              color_formatter = ColoredFormatter(self.COLOR_FORMAT)
      
              console = logging.StreamHandler()
              console.setFormatter(color_formatter)
      
              self.addHandler(console)
              return
      
      
      logging.setLoggerClass(ColoredLogger)
      

      【讨论】:

      • 如何回答这个问题?颜色呢?
      • 我还没试过;乍一看,至少对我来说有点复杂;但无论如何我都会试一试;感谢所有提示和建议!
      猜你喜欢
      • 2020-08-22
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多