Removing colored jewelery from strings before writing them to a log file

I use the ruby ​​logger as follows:

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

Where MultiIO is the class I got from this answer . This works fine, mostly, but I use 'colored' rubygem to get color output on the terminal. Unfortunately, this also ends in the log file, since ANSI escapes the view of [32mPASS[0m or some similar non-printable characters.

What is the best approach to disinfect log lines while preserving colors for tty lines? I am not against Logger or MultiIO monkey patches, but I absolutely do not want two different calls for the log file and the screen.

+8
ruby logging colors ansi-escape
source share
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)) 
+11
source share

From 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 
+6
source share

To remove ASCII colors, I would recommend

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

All Articles