Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log to different logger based on call from Sidekiq or Rails

Tags:

sidekiq

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.

like image 589
Old Pro Avatar asked Aug 07 '13 19:08

Old Pro


People also ask

Is Sidekiq multi threaded?

Sidekiq handles concurrency by using multiple threads in its process. This way, it can process multiple jobs at once, each thread processing one job at a time. By default, Sidekiq uses 10 threads per process.

How does Sidekiq work in Rails?

Sidekiq server process pulls jobs from the queue in Redis and processes them. Like your web processes, Sidekiq boots Rails so your jobs and workers have the full Rails API, including Active Record, available for use. The server will instantiate the worker and call perform with the given arguments.

What is Sidekiq in Ruby on Rails?

Sidekiq is a free and open-source Ruby job scheduler that was created by Mike Perham. Ruby programming language is one of our most used and well-mastered tools we respect and love.


1 Answers

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.

like image 129
Winfield Avatar answered Jan 02 '23 20:01

Winfield