Custom Logging in Ruby on Rails
by vyolian
I’m one of those developers that likes to abuse standard output in development. In my rails development, I would use ‘puts variable’ everywhere. But sometimes, my debug print statements get clobbered with rail’s default logging of requests and SQL queries.
I’m aware there’s a debugger… but I find using puts quicker. This is especially the case when I just want to see a pattern within an execution or loop rather than tracing variables at each step.
Anyway, here’s how to build a console window that’s devoted solely for debug print statements. You may also find this useful for devoting a log file just to search, auditing, etc. Here are the very basics:
Create Your Custom Logger
#custom_logger.rb
class CustomLogger < Logger
def format_message(severity, timestamp, progname, msg)
"#{msg}\n"
end
end
logfile = File.open(RAILS_ROOT + '/log/custom.log', 'a') #create log file
logfile.sync = true #automatically flushes data to file
CUSTOM_LOGGER = CustomLogger.new(logfile) #constant accessible anywhere
Load CustomLogger From Environment
#in development.rb require "custom_logger"
Use CustomLogger
#in any controller, view or model
CUSTOM_LOGGER.info("info from custom logger")
Finally, create your debug console using
tail -f log/custom.log
Resources
http://maintainable.com/articles/rails_logging_tips (very thorough rails logging article)
http://www.themomorohoax.com/2009/02/09/use-debugger (rails debugger)
http://log4r.sourceforge.net/manual.html (log4r)
Works like a charm. Well written article!
Awesome.. Working cool..
Coupled with an initializer and a singleton this is even better. We can just CustomerLogger.logger.info “message”
Here is a gem that makes log customization really easy:
https://github.com/johmas/itslog
So I added to the code so that it will put out a Growl notification every time you hit a notification. You will need to have “require ‘ruby-growl’” in your gemfile. See http://segment7.net/projects/ruby/growl/ for details!
#custom_logger.rb
class CustomLogger < Logger
def format_message(severity, timestamp, progname, msg)
regex = /(([Ee][Rr][Rr][Oo][Rr])|())([^,]*)(,(.*))?/
match = regex.match(msg)
if match[1] != ""
error = true
subject = "ERROR: "
else
error = false
subject = ""
end
match[4].present? ? subject += match[4] : subject = "subject_error"
if match[6].present?
GROWL.notify "ruby-growl Notification", subject, match[6], 0, error
else
GROWL.notify "ruby-growl Notification", subject, "", 0, error
end
"[#{timestamp.strftime("%I:%M:%S%p")} JON] #{msg}\n\n"
end
end
logfile = File.open(RAILS_ROOT + '/log/custom.log', 'a') #create log file
logfile.sync = true #automatically flushes data to file
GROWL = Growl.new "127.0.0.1", "ruby-growl", ["ruby-growl Notification"], nil, "growl_password"
CUSTOM_LOGGER = CustomLogger.new(logfile) #constant accessible anywhere
[...] http://ianma.wordpress.com/2009/04/08/custom-logging-in-ruby-on-rails/ [...]
[...] that a valid way to implement [...]