Custom log files in Rails 3
In addition to outputting lots of useful information, the Rails logger can be a useful debugging tool. But debugging with the log file can become frustrating as it will be cluttered with default content. The solution to this problem is to create a custom logger and log file for such output.
The easiest way to do this is to create a global log function, enable it in your development environment, and make sure that calls to it don’t do anything in other environments.
To start, add a file to the initializers directory that will initialize the custom logger. (My dev environment is called “garret”, not the traditional “development”, so I’ll be referring to the environment as such in subsequent code.)
My filename: <Rails.root>/config/initializers/garret_logging.rb
The logic in this file should check if the current environment is the “garret” environment, and if so, add our global logging function. If it’s a different environment, we’ll still add the global logging function, it just won’t do anything.
Let’s call the global function “glog”, since that’s what I call it.
As a quick aside, there’s no such thing as a global function in Ruby. If you try to create a function at the highest scope Ruby will attach it as a method on the Object class. Since everything in Ruby is an object, and the Object class is the root class, adding a method to the Object class basically makes it behave exactly like a global function.
The code is pretty straight forward so I’ll put in below without much more explanation. Here’s what goes in garret_logging.rb.
if Rails.env == "garret" class GarretLogger < Logger def format_message(severity, timestamp, progname, msg) "#{msg}\n" end end logfile = File.open(Rails.root + 'log/gdev.log', File::WRONLY|File::APPEND|File::CREAT, 0666) logfile.sync = true Glog = GarretLogger.new(logfile) class Object def glog(mssg) Glog.info(mssg) end end else class Object def glog(mssg) end end end
The Rails Logger class is extended but simplified so that there’s no severity level. While in the “garret” development environment, “foobar” will get logged to the custom log file (<Rails.root>/log/gdev.log) simply by putting:
glog "foobar"
And in any other environment, the above will do nothing, so production won’t crash if you leave in a few glog statements.