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.
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))
For removal of ANSI colors, I would recommend
string_with_ascii = "..."
string_no_ascii = string_with_ascii.gsub(/\e\[([;\d]+)?m/, '')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With