Rails 7.1 Adds Support For Logging Background Job Enqueue Callers.

ActiveJob is used to run tasks in the background, helping us offload long-running tasks to the background job and keep our application responsive.

However, when a job fails, whether due to network issues or database unavailability, it can sometimes be difficult to trace the source of the problem.

Before

When a job is enqueued using ActiveJob, the logs provide information about the job being added to the queue, but they lack detailed context about where the job was enqueued in the codebase for effective backtracking.

This lack of visibility made debugging more difficult, especially in large codebases where jobs might be enqueued from various places.

After

Rails 7.1 adds support for logging background job enqueue callers by adding backtrace support to ActiveJob’s existing logging capabilities.

We need to enable the verbose_enqueue_logs option in our application’s configuration. However, Rails 7.1 ships with this configuration by default in development mode.

It highlights the code that enqueued the background job in the logs, including the file and line number.

# config/environments/development.rb

config.active_job.verbose_enqueue_logs = true

Here’s what the log output looks like with verbose_enqueue_logs enabled:

[ActiveJob] Enqueued UserInvitationJob (Job ID: ab528951-41fb-4c48-9129-3171791c27d6) to Sidekiq(default)
[ActiveJob]  app/models/user.rb:25 in `send_user_invitation`

In the above logs, we can see that the UserInvitationJob was enqueued from the send_user_invitation method in the User model, providing us with a clear picture of the job’s origin.

Note

It is not recommended to enable verbose_enqueue_logs in production due to potential performance impacts, as Kernel#caller, which generates backtraces, can be relatively slow.

Need help on your Ruby on Rails or React project?

Join Our Newsletter