Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing color decorations from strings before writing them to logfile

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.

like image 668
wim Avatar asked Apr 16 '13 08:04

wim


3 Answers

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))
like image 155
wim Avatar answered Nov 16 '22 17:11

wim


For removal of ANSI colors, I would recommend

string_with_ascii = "..."
string_no_ascii = string_with_ascii.gsub(/\e\[([;\d]+)?m/, '')
like image 39
Haris Krajina Avatar answered Nov 16 '22 18:11

Haris Krajina


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
like image 6
Leventix Avatar answered Nov 16 '22 17:11

Leventix