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

2024-09-26 18:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

由于我们在调试时记录了大量的信息,所以我想找到一种方法,将coloredlogsdoes这样的日志文件着色到打印到终端的日志上。我看了coloredlogs,但它似乎只能在使用VIM时将彩色日志打印到文件中。有人知道用python将彩色日志打印到文件中的方法吗?这个文件可以用wordpad这样的程序打开?(可能是.rtf文件)。在


Tags: 文件方法脚本信息终端记录控制器语句
1条回答
网友
1楼 · 发布于 2024-09-26 18:17:10

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

相关问题 更多 >

    热门问题