在将字符串写入日志文件之前从字符串中删除颜色装饰

时间:2022-02-09 06:22:25

I use the ruby logger like this:

我像这样使用ruby记录器:

$logger = Logger.new MultiIO.new($stdout, log_file)

Where the MultiIO is a class I got from this answer. This works great, mostly, but I am using 'colored' rubygem to give coloured output on the terminal. Unfortunately this ends up in the logfile too as ANSI escapes looking like [32mPASS[0m or some similar non-printable characters rubbish.

MultiIO是我从这个答案得到的课程。这主要是很好用的,但我使用'有色'rubygem在终端上给出彩色输出。不幸的是,这也会在日志文件中结束,因为ANSI转义看起来像[32mPASS [0m或一些类似的不可打印的字符垃圾。

What is the best approach to sanitise the logfile strings whilst keeping colours for the tty strings? I don't mind monkey-patching Logger or MultiIO, but I absolutely don't want two different calls for logfile and screen.

清除日志文件字符串同时保持tty字符串颜色的最佳方法是什么?我不介意猴子修补Logger或MultiIO,但我绝对不希望对日志文件和屏幕进行两次不同的调用。

3 个解决方案

#1


11  

This is my current solution

这是我目前的解决方案

class ColourBlind
  def initialize(*targets)
     @targets = targets
  end

  def write(*args)
    @targets.each {|t| t.write(*args.map {|x| x.gsub(/\e\[(\d+)m/, '')}.compact)}
  end

  def close
    @targets.each(&:close)
  end
end

And then:

接着:

$logger = Logger.new MultiIO.new($stdout, ColourBlind.new(log_file))

#2


6  

From the colorize gem:

从着色宝石:

class String
  REGEXP_PATTERN = /\033\[([0-9]+);([0-9]+);([0-9]+)m(.+?)\033\[0m|([^\033]+)/m

  def uncolorize
    self.scan(REGEXP_PATTERN).inject("") do |str, match|
      str << (match[3] || match[4])
    end
  end
end

#3


4  

For removal of ASCII colors, I would recommend

为了删除ASCII颜色,我建议

string_with_ascii = "..."
string_no_ascii = string_with_ascii.gsub(/\e\[([;\d]+)?m/, '')

#1


11  

This is my current solution

这是我目前的解决方案

class ColourBlind
  def initialize(*targets)
     @targets = targets
  end

  def write(*args)
    @targets.each {|t| t.write(*args.map {|x| x.gsub(/\e\[(\d+)m/, '')}.compact)}
  end

  def close
    @targets.each(&:close)
  end
end

And then:

接着:

$logger = Logger.new MultiIO.new($stdout, ColourBlind.new(log_file))

#2


6  

From the colorize gem:

从着色宝石:

class String
  REGEXP_PATTERN = /\033\[([0-9]+);([0-9]+);([0-9]+)m(.+?)\033\[0m|([^\033]+)/m

  def uncolorize
    self.scan(REGEXP_PATTERN).inject("") do |str, match|
      str << (match[3] || match[4])
    end
  end
end

#3


4  

For removal of ASCII colors, I would recommend

为了删除ASCII颜色,我建议

string_with_ascii = "..."
string_no_ascii = string_with_ascii.gsub(/\e\[([;\d]+)?m/, '')