Log to different logger based on call from Sidekiq or Rails

自古美人都是妖i 提交于 2019-12-05 18:20:37

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18112310/log-to-different-logger-based-on-call-from-sidekiq-or-rails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!