If you have ever tried to customize the Logger.datetime_format attribute in rails to get timestamps in your logs, you probably noticed that it didn't work. This is not normally a problem because the standard log format in rails works fine for most people (and support tools, like log analyzers, would not work if you messed with the log formats too much). Unfortunately, if you're including a rails environment in a non-rails application (i.e. a DRb daemon which needs to access your ActiveRecord models), Logger.datetime_format won't work there either.

If you haven't encountered this anomaly before, let me save you some grepping. The reason why datetime_format doesn't work can be found in activesupport-1.3.1/lib/active_support/clean_logger.rb:

class Logger #:nodoc:
...
  private
    alias old_format_message format_message
...
    if method_defined?(:formatter=)
      def format_message(severity, timestamp, progname, msg)
        "#{msg}\n"  # We lose formatting here!
      end
    else
      def format_message(severity, timestamp, msg, progname)
        "#{msg}\n"  # Or we lose our formatting here!
      end
    end
...
end
So, if you want to have a rails environment in your DRb server but also have control over your log format, you can use this quick workaround:
...
#Somewhere in the initialization code for your server
require 'environment' # referring to RAILS_ROOT/config/environment.rb

# Undo the damage done by activesupport.
class Logger
    private
    alias format_message old_format_message
end

# Now you can instantiate a Logger and set your datetime_format and it should work
...
This is why I love ruby so much. If this were Java, I'd be digging through some gomer's jar file, changing their code, and recompiling the entire world before I could make a simple workaround like this.

Leave a Reply