Question

I use the ruby logger like this:

$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.

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.

Was it helpful?

Solution

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))

OTHER TIPS

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

For removal of ANSI colors, I would recommend

string_with_ascii = "..."
string_no_ascii = string_with_ascii.gsub(/\e\[([;\d]+)?m/, '')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top