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)

About these ads