|
This post originated from an RSS feed registered with Ruby Buzz
by Guy Naor.
|
Original Post: Improving the Rails Logger
Feed Title: Famundo - The Dev Blog
Feed URL: http://devblog.famundo.com/xml/rss/feed.xml
Feed Description: A blog describing the development and related technologies involved in creating famundo.com - a family management sytem written using Ruby On Rails and postgres
|
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Guy Naor
Latest Posts From Famundo - The Dev Blog
|
|
The rails logger is VERY useful. It amazes me that I don't really feel I need a debugger in rails (after using one for years in Visual C++) and a lot of it is the console and the logger.
One thing missing from the logger, is the process id of the rails instance that is logging. This is important when you have more than one instance of your app serving requests through fcgi or mongrel or whatever. It's needed in order to enable us to see how the request was handled, as we can extract only logs that pertain to this specific request, even when it's mixed with other requests.
Using the fact that all classes in Ruby are open, we modify the logger to do what we need. Either create a file in your lib directory, or anywhere else you prefer, and in your config/environment.rb add the line:
require 'pid_logger'
The file should include the following (most of it extracted from the default rails logger):
class Logger
private
if method_defined?(:formatter=)
log_str = ""
def format_message(severity, timestamp, progname, msg)
log_str = "[#{$$}][#{severity[0...1]}] msg\n"
end
else
def format_message(severity, timestamp, msg, progname)
log_str = "[#{$$}][#{severity[0...1]}] msg\n"
end
end
end
One more possible change that I use in some applications, is to color the background of debug messages I sent to the logger. The change here is also very slight. Here is the same file, but with the added coloring of the output with a green or red background depending on severity, when a line start with 4 or more > + - = characters (e.g: ">>>>>>>> This is a test" will have the >>>>>>>> part with a red backround if error, and green otherwize). It makes finding the log messages very eash.
class Logger
private
if method_defined?(:formatter=)
log_str = ""
def format_message(severity, timestamp, progname, msg)
log_str = "[#{$$}][#{severity[0...1]}] #{color_special_msg(msg, severity)}\n"
end
else
def format_message(severity, timestamp, msg, progname)
log_str = "[#{$$}][#{severity[0...1]}] #{color_special_msg(msg, severity)}\n"
end
end
def color_special_msg msg, severity
sub_color = severity[0...1] == 'E' ? '41' : '42'
msg.sub(/^((\*|>|\+|-|=){4,})/, "\033[1;#{sub_color}m\\1\033[0m")
end
end
And as you can see, adding whatever changes you want to the logger is easy. So go ahead and make it work the way YOU want it to.
Read: Improving the Rails Logger