ruby-on-railsrubyloggingrails-activejob

Rails.logger not working in ApplicationJob.before_perform


I'm using ActiveJob to manage my jobs, and I have the following ApplicationJob:

class ApplicationJob < ActiveJob::Base
  # [...]

  before_perform do |job|
    Rails.logger.info 'before_perform callback triggered' # This doesn't log
  end

  # [...]
end

Additionally, I have another job that inherits from ApplicationJob:

class MyJob < ApplicationJob
  def perform
    # do something
    Rails.logger.info 'perform method called' # This logs correctly
  end
end

I've configured my logger to write to a file, and while the logs inside the perform method are written to the file as expected, the logs from the before_perform callback don't appear at all.

For context, I'm invoking the jobs using both perform_now and perform_later methods, but neither seems to trigger the before_perform log.

Thanks in advance!


Solution

  • While I can't explain the behavior, there are 2 things you could try.

    Option 1 is to use Sidekiq.logger if Sidekiq is what runs the jobs.

    Option 2 is to define logger inside the Job class, which is not too elegant, but does the job. Like so:

    class ApplicationJob < ActiveJob::Base
      # [...]
    
      before_perform do |job|
        say 'before_perform callback triggered' # This should log into the job_runner.log
      end
    
      # [...]
    
      def say(what)
        unless @logger
          @logger = Logger.new(File.join(Rails.root, 'log', 'job_runner.log'))
        end
    
        @logger.info(what)
      end
    end