Custom loggers in rails
I ran into some problems trying to setup a custom logger in rails which I thought I would share to ease someone else’s pain. Everything I read said that to setup a custom logger instance, I should set config.logger in my environment.rb, e.g.
environment.rb:
config.logger = MyLogger.new(config.log_path)
However, I just could not get this to have any effect! It turns out that this was because I was starting up my server using script/server using mongrel. Using “script/server webrick”, or “mongrel_rails start” worked just fine.
I think this is caused by code in the mongrel.rb file that script/server uses which loads just the logging environment (but not my environment) in order to figure out which log file to tail
railties/lib/server/mongrel.rb:
require 'initializer'
Rails::Initializer.run(:initialize_logger)
Loading the environment here causes the RAILS_DEFAULT_LOGGER constant to get set, and thus when my config finally gets loaded when mongrel itself starts up, the config.logger I set gets ignored as the rails init code does nothing if RAILS_DEFAULT_LOGGER is set:
railties/lib/initializer.rb:
def initialize_logger
# if the environment has explicitly defined a logger, use it
return if defined?(RAILS_DEFAULT_LOGGER)
...
end
The patch on this bug report seems related, but didn’t fix my problem.
I’m too much a rails newb to figure out the right way to patch this, hopefully someone with more of a clue will see this blog entry and submit a patch