[英]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 解决方案留给其他人。
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
.然后我将它设置为特定
FileHandler
的Formatter
程序。
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}")
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.