Last Updated: February 25, 2016
·
3.033K
· yanhaoyang

Tagged logs written by sidekiq workers in Rails log

Rails itself writes tagged logs in Rails log files. Sidekiq workers can also write logs into Rails log files. But these logs are not tagged by default, therefore, it is hard to identify which logs are generated by a specific worker.

With Sidekiq's middleware, it is quit easy to convert those logs into tagged logs.

module Sidekiq
  module Middleware
    module Server
      class TaggedLogger

        def call(worker, item, queue)
          tag = "#{worker.class.to_s} #{SecureRandom.hex(12)}"
          ::Rails.logger.tagged(tag) do
            job_info = "Start at #{Time.now.to_default_s}: #{item.inspect}"
            ::Rails.logger.info(job_info)
            yield
          end
        end

      end
    end
  end
end

Sidekiq.configure_server do |config|
  config.server_middleware do |chain|
    chain.add Sidekiq::Middleware::Server::TaggedLogger
  end
end