【问题标题】:Python: How to color logs while printing to a file?Python:如何在打印到文件时为日志着色?
【发布时间】:2019-03-14 14:23:39
【问题描述】:

我正在做的事情的一点背景。我正在工业控制器上通过不同的编程语言运行一些 python 脚本。由于我没有直接运行 python 脚本,我无法从终端查看任何打印或日志语句,因此我需要将详细日志发送到日志文件。

由于我们在调试时记录了很多信息,我想找到一种方法来为日志文件着色,例如 coloredlogs 对打印到终端的日志进行着色。我查看了coloredlogs,但它似乎只能在使用VIM 时将彩色日志打印到文件中。有谁知道一种使用 python 将彩色日志打印到文件的方法,该文件可以用诸如写字板之类的程序打开? (可能是.rtf 文件)。

【问题讨论】:

  • 您可以输入任何颜色信息(以纯文本形式),然后使用一些日志查看器(如 vim)解析为颜色。或仅按关键字过滤。事实上,我认为日志级别(信息、错误等)就足够了。
  • 我希望我不需要在工业控制器上安装日志查看器。控制器使用 Windows,所以如果需要我可以,但我希望使用本机安装的程序之一。话虽如此,我应该如何将颜色信息添加到日志输出中?
  • 如果没有颜色,你用什么编辑器来检查日志?记事本?
  • 目前我使用记事本,因为我没有使用颜色。当我开始使用颜色时,我可能会使用写字板。
  • notepad++ 可以突出显示常见的日志文件(如果没有,请查找插件)。为什么不试试?你需要一个好的编辑器(我并不是说 notepad++ 是最好的)。

标签: python python-3.x windows logging colors


【解决方案1】:

使用Windows PowerShellGet-Content函数打印包含ANSI escape sequences的文件来为日志着色是一种解决方案。

例如:

import coloredlogs
import logging

# Create a logger object.
logger = logging.getLogger(__name__)

# Create a filehandler object
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)

# Create a ColoredFormatter to use as formatter for the FileHandler
formatter = coloredlogs.ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)

# Install the coloredlogs module on the root logger
coloredlogs.install(level='DEBUG')

logger.debug("this is a debugging message")
logger.info("this is an informational message")
logger.warning("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a critical message")

打开Windows PowerShell 时,您可以使用Get-Content .\spam.log 以彩色打印日志。

【讨论】:

  • 我认为这可以满足我的需求。 Powershell 的默认配色方案不是很好,但我可以在 cmd 提示符下使用 type spam.log。我没有意识到 ANSI 转义序列可以被 Powershell 和命令提示符读取。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-08-10
  • 2010-09-27
  • 2018-08-15
  • 1970-01-01
  • 2020-03-17
  • 2013-03-19
  • 1970-01-01
相关资源
最近更新 更多