简体   繁体   English

从 output 日志文件中排除 ANSI 转义序列

[英]Exclude ANSI escape sequences from output log file

I have set up a class of colours to make the stdout easier to read in case of warnings.我已经设置了 class 颜色,以便在出现警告时更易于阅读标准输出。 I also want to write all print statements to a log file.我还想将所有打印语句写入日志文件。

# Colour set up
class colours:
    warning = '\033[93m'
    colour1 = '\033[94m'
    colour2 = '\033[1m'
    terminate = '\033[0m'

# Logger set up
class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open(“output.log”, "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

sys.stdout = Logger()

# Example
print colours.warning + ‘WARNING!’ + colours.terminate

*in colour*:$ WARNING!

*in output.log*: [93mWARNING!

Is there any way to either write characters that will also colour the output.log file or print in colour to the stdout but not include '[94m' in the log file?有什么方法可以写入也会为 output.log 文件着色的字符,或者以彩色打印到标准输出但不在日志文件中包含“[94m”? I'd prefer not to require an install of any non-native python packages for user ease.为了方便用户,我不想要求安装任何非本地 python 包。

Use a regexp like \\x1b\\[[0-9;]*m to strip out the ANSI codes when writing to the output.log object? 在写入output.log对象时,使用\\x1b\\[[0-9;]*m这样的正则表达式来\\x1b\\[[0-9;]*m ANSI代码吗?

Ie

import re

ansi_re = re.compile(r'\x1b\[[0-9;]*m')

# ...

self.log.write(re.sub(ansi_re, '', message))

I know, that is an old thread, but I want to leave my improved (in my mind) solution of @AKX for other people.我知道,这是一个旧线程,但我想将我改进的(在我看来)@AKX 解决方案留给其他人。

Improved solution改进的解决方案

To automate what was done when logging, ie re.sub(...) one can create a custom formatter.为了自动化日志记录时所做的事情,即re.sub(...)可以创建一个自定义格式化程序。

class TermEscapeCodeFormatter(logging.Formatter):
    """A class to strip the escape codes from the """
    def __init__(self, fmt=None, datefmt=None, style='%', validate=True):
        super().__init__(fmt, datefmt, style, validate)

    def format(self, record):
        escape_re = re.compile(r'\x1b\[[0-9;]*m')
        record.msg = re.sub(escape_re, "", str(record.msg))
        return super().format(record)

Then I set it as a Formatter for a particular FileHandler .然后我将它设置为特定FileHandlerFormatter程序。

def main():
    lger = logging.getLogger("test_hw")
    lger.setLevel(logging.INFO)

    stdo = logging.StreamHandler()
    stdo.setLevel(logging.INFO)

    fhdr = logging.FileHandler("fname.txt", "w")
    fhdr.setLevel(logging.INFO)

    fmer = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    stdo.setFormatter(fmer)
    cfmer = TermEscapeCodeFormatter('%(asctime)s - %(levelname)s - %(message)s')
    fhdr.setFormatter(cfmer)

    lger.addHandler(stdo)
    lger.addHandler(fhdr)

Now one can use one logger with coloring (I use Colorama ) to output to stdout with the colors enabled and to file with them disabled.现在可以使用一个带颜色的记录器(我使用Colorama )到 output 到标准输出,启用 colors 并禁用它们进行归档。

    lger.info(f"value = {Style.BRIGHT}{value :>5.2f} V{Style.RESET_ALL}")

Flaws瑕疵

In this version works only for ANSI terminals, but one could adapt the regexp to match other patterns.在此版本中仅适用于 ANSI 终端,但可以调整正则表达式以匹配其他模式。

There is no defaults keyword argument as per newest (3.10 I believe) Python version.根据最新(我相信是 3.10)Python 版本,没有defaults关键字参数。 I use 3.8.我用的是3.8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将带有ANSI转义序列的字符串写入文件 - Writing string with ANSI escape sequences to file ANSI 转义序列在 Cygwin 中失败 - ANSI Escape Sequences Fail in Cygwin 如何从 python 中的字符串中删除 ANSI 转义序列 - How can I remove the ANSI escape sequences from a string in python 解析标有ANSI颜色转义序列的数据 - parsing data tagged with ANSI color escape sequences 从文件中读取 utf-8 转义序列 - Reading utf-8 escape sequences from a file 如何创建支持ANSI转义码序列的可滚动控制台应用程序 - How to create scrollable console application that support ANSI escape code sequences ANSI 颜色转义序列不同的前景和背景颜色 256 colors - ANSI Color Escape Sequences Different Foreground and Background color with 256 colors 如何在 Windows 10 控制台中使用对 ANSI 转义序列的新支持? - How to use the new support for ANSI escape sequences in the Windows 10 console? 如何防止Python脚本中的ANSI转义序列与zsh RPROMPT和光标位置混淆? - How can I prevent ANSI escape sequences in my Python script from messing with my zsh RPROMPT and cursor positions? 如何从日志消息中制作`FileHandler`条终端转义序列(颜色)? - How to make a `FileHandler` strip terminal escape sequences (colors) from a log message?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM