Search code examples
ruby-on-railsmultithreadingipcjrubyjrubyonrails

Logging inside threads in a Rails application


I've got a Rails application in which a small number of actions require significant computation time. Rather than going through the complexity of managing these actions as background tasks, I've found that I can split the processing into multiple threads and by using JRuby with a multicore sever, I can ensure that all threads complete in a reasonable time. (The customer has already expressed a strong interest in keeping this approach vs. running tasks in the background.)

The problem is that writing to the Rails logger doesn't work within these threads. Nothing shows up in the log file. I found a few references to this problem but no solutions. I wouldn't mind inserting puts in my code to help with debugging but stdout seems to be eaten up by the glassfish gem app server.

Has anyone successfully done logging inside a Rails ruby thread without creating a new log each time?


Solution

  • I was scratching my head with the same problem. For me the answer was as follows:

    Thread.new do
      begin
        ...
      ensure
        Rails.logger.flush
      end
    end