Skip to content

Customize Sidekiq logger

Toshimitsu Takahashi edited this page Oct 7, 2020 · 3 revisions
  • Add Sidekiq context to logs
  • Replace error handler with a custom handler that combines default 3 logs into 1 log.

config/initializers/sidekiq.rb

Sidekiq 6 or later
Sidekiq.configure_server do |config|
  # logging with sidekiq context
  config.logger = Rails.logger.child
  config.logger.before_log = lambda do |data|
    ctx = Thread.current[:sidekiq_context]
    break unless ctx
    items = ctx.map {|c| c.split(' ') }.flatten
    data[:sidekiq_context] = items if items.any?
  end

  # Replace default error handler
  config.error_handlers.pop
  config.error_handlers << lambda do |ex, ctx|
    Sidekiq.logger.warn(ex, job: ctx[:job]) # except job_str
  end
end
Sidekiq 5 or earlier
Sidekiq::Logging.logger = Rails.logger.child

Sidekiq.configure_server do |config|
  # logging with sidekiq context
  Sidekiq::Logging.logger.before_log = lambda do |data|
    ctx = Thread.current[:sidekiq_context]
    break unless ctx
    items = ctx.map {|c| c.split(' ') }.flatten
    data[:sidekiq_context] = items if items.any?
  end

  # Replace default error handler
  config.error_handlers.pop
  config.error_handlers << lambda do |ex, ctx|
    Sidekiq::Logging.logger.warn(ex, job: ctx[:job]) # except job_str
  end
end