Logging from initializers and plugings
Following code has been tested with Rails 2.3.5 .
If you put log messages in rails initializers then they do not show up in console.
# ~/config/initializers/session_store.rb Rails.logger.info "I am within initializer"
Start the server and you won’t see the message that was put in initializer.
ruby script/server
The weird thing is that log message did not show up but the code did not blow up either. Some would say that using RAILS_DEFAULT_LOGGER.info would solve the problem. That is not true.
This problem is not restricted to initializers only. If you put in some log messages in init.rb of a plugin then also you will find that those log message do not appear on console.
logs are going to development.log
When rails starts server then it calls initialize_logger . This is where Rails.logger is mapped to RAILS_DEFAULT_LOGGER. Since rails loads gems, plugins and initializers after invoking initialize_logger, one can use Rails.logger in gems, plugins and in initializers.
Since rails is rack compliant application, while initializing rails script/server introduces a rack middleware called LogTailer
use Rails::Rack::LogTailer unless options[:detach]
As the name suggests, the job of this middleware is to tail the log of development.log .
If you put in log messages in plugin or in initializers then those log messages go to development.log . After the initialization is done then script/server starts tailing the log file.
However tail only reports the new log messages. Log messages already written to development.log are not reported to console. This explains why you did not see log messages on console.
Also note that log messages are always written to development.log . On console we see the tail of that log.
A quick solution
One solution to this problem is to use puts but if you are debugging something on server then those messages would not appear on log. If you use Rails.logger then those messages would not appear on your console. A quick solution is to show all the existing messages from the log file at the end of initialization process.
Add following code in an initializer and you will see log messages from initializers and plugins.
# ~/config/initializers/zzz_log_output_to_console.rb
File.open(Rails.root.join('log', 'development.log'), "r") do |logfile|
while (line = logfile.gets)
puts line
end
end
Rails loads all initializers file in alphabetical order. Since I want all the accumulated messages on the console, I want my initializer to be last one to execute. Hence the name starts with z.