Sidekiq is probably the most popular background processing framework for Ruby. Not only is it fast and reliable, it also has the concept of a middleware, which lets you hook into the lifecycle of jobs.

Some of Sidekiq’s own features are implemented as a middleware, for example auto-retrying of jobs. We wanna start with something simpler, and add a middleware that simply prints the name and list of arguments provided of the job that’s about to be executed to the Rails log.

The middleware protocol is similar to the one used by Rack - you implement a single method named #call, which takes three arguments: worker, item, and queue:

  • worker holds the worker instance that will process the job
  • item is a hash that holds information about arguments, the job ID, when the job was created and when it was enqueued,…
  • queue holds the queue name the job is fetched from

Let’s add the following file to our Rails application:

1
2
3
4
5
6
7
8
9
10
11
12
# lib/sidekiq/middleware/server/argument_logging.rb
module Sidekiq::Middleware::Server
  class ArgumentLogging
    def call(worker, item, queue)
      klass = item['class']
      args = item['args']
      Rails.logger.info("Performing #{klass} with arguments: #{args}")

      yield
    end
  end
end

Now we need to tell Sidekiq to add our custom middleware. For this, we’ll create a custom initializer file and place the following code in there:

1
2
3
4
5
6
7
8
# config/initializers/sidekiq.rb
require './lib/sidekiq/middleware/server/argument_logging'

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

Next we restart sidekiq (bundle exec sidekiq), and enqueue new job. Now you should see something like this in your Rails’ development.log file:

1
Performing TestWorker with arguments: [“Sidekiq is awesome!“, 10]