In a previous post I showed you a simple way to get beautiful, easy-to-read logs in your Rails 3.2 application. Rails 4 changed the game again; for Rails 3.2 or earlier, refer to my earlier post; but for Rails 4 read on…
It’s really easy. Just make a new file in your ‘config/initializers’ directory called something like ‘log_formatting.rb’ and paste into it the following code. Restart your app, and voila: pretty logs again!
UPDATED. Konrad’s comment below was correct. I’ve altered this code to work with both the regular logger and the new tagged logger. Now you can configure your logger as
config.logger = ActiveSupport::Logger.new('your_app.log')
or
config.logger = ActiveSupport::TaggedLogging.new(Logger.new('your_app.log'))
… both will work. Here’s the updated monkey patch:
class ActiveSupport::Logger::SimpleFormatter SEVERITY_TO_TAG_MAP = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'} SEVERITY_TO_COLOR_MAP = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'} USE_HUMOROUS_SEVERITIES = true def call(severity, time, progname, msg) if USE_HUMOROUS_SEVERITIES formatted_severity = sprintf("%-3s",SEVERITY_TO_TAG_MAP[severity]) else formatted_severity = sprintf("%-5s",severity) end formatted_time = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3) color = SEVERITY_TO_COLOR_MAP[severity] "\033[0;37m#{formatted_time}\033[0m [\033[#{color}m#{formatted_severity}\033[0m] #{msg.strip} (pid:#{$$})\n" end end
That did not work for me, due to ActiveSupport::TaggedLogging (http://api.rubyonrails.org/classes/ActiveSupport/TaggedLogging.html). Due to the new formatter there was no method tagged which resulted in a broken application. What did help was to simply update the class ActiveSupport::Logger::SimpleFormatter and not assigning a new formatter at all.
TaggedLogger is also available in Rails 3.2 (see: http://guides.rubyonrails.org/3_2_release_notes.html for instance) … So, can I use this [Rails 4] version, or do I have to futz with the 3.2 version you provided in your earlier blog post last year to get this?
Thanks!
I haven’t tried TaggedLogger in 3.2, so I can’t say. Are you interested in giving it a try and reporting back?
Found out in railties (https://github.com/rails/rails/blob/master/railties/lib/rails/application/bootstrap.rb#L43) that a formatter for the default logger can be defined in the Rails config (config.log_formatter). Therefore I think it’s better to define a custom formatter in ./lib and assigning this to log_formatter instead of customizing the simple formatter.
thank you so much for posting this, it was beyond helpful!
I’ve been using this patch for a while now and after copying it into several projects I broke down and just created a gem.
https://github.com/phallguy/shog