gpt4 book ai didi

Python:如何在打印到文件时为日志着色?

转载 作者:行者123 更新时间:2023-12-01 08:12:20 30 4
gpt4 key购买 nike

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

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

最佳答案

可以使用 Windows PowerShell Get-Content 函数打印包含 ANSI 转义序列 的文件来为日志。

例如:

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 以彩色打印日志。

关于Python:如何在打印到文件时为日志着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55164961/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com