11

I have an Rails 3.2 based app that uses Sidekiq 2.12 to run background jobs. The Sidekiq jobs can call the same methods as the interactive Rails app. I would like the methods to log to the Sidekiq log when called from Sidekiq and log to the Rails log when called from Rails. I am looking for a clean way to do this but so far have come up empty.

In both environments, both Sidekiq::Logging.logger and Rails.logger are defined and work.

  • I do not want to inspect the call stack on every logging attempt in order to pick the right loggger.
  • I do not want to pass a log object as a function parameter to every function that might be called from both Sidekiq and Rails.

I think probably the right thing do to is to have Sidekiq replace the Rails logger with its logger during the startup process and then always log to the Rails logger, but I can't find an initializer hook that runs after the Rails logger is set up but before Sidekiq jobs are started and is only run by Sidekiq.

Is there such a hook? If so, please tell me about it. If not, please provide other suggestions for how to cleanly redirect logging output based on the Sidekiq vs Rails running environment.

Old Pro
  • 24,624
  • 7
  • 58
  • 106

1 Answers1

31

Both Sidekiq and Rails use Logger compliant classes from the Ruby StdLib.

You should be able to re-configure the Rails logger to use the Sidekiq logger in the Sidekiq server config block. Find/create a file like config/inititializers/sidekiq.rb:

Sidekiq.configure_server do |config|
  Rails.logger = Sidekiq::Logging.logger

  # Sidekiq other server config
  ...
end

The block passed to the Sidekiq.configure_server call is only executed within the Server component of the Sidekiq backend, not within the client running in your Rails app server or console.

Winfield
  • 18,985
  • 3
  • 52
  • 65
  • As far as I can tell, that will cause the Rails app to use the Sidekiq logger, too. I want the Rail app (answering web requests) to log to the Rails logger and the Sidekiq processes to log to the Sidekiq logger. – Old Pro Aug 09 '13 at 22:16
  • 6
    That is not correct. The block passed to the Sidekiq.configure_server call is only executed within the Server component of the Sidekiq backend, not within the client running in your Rails app server or console. – Winfield Aug 09 '13 at 23:13