Rails 7 adds Marginalia to Query Logs


Rails provides great Query Logs detailing exact database queries made. It looks something like this,

User Load (0.3ms)  SELECT `users`.* FROM `users`
WHERE `users`.`id` = 1234567890
LIMIT 1

However, when debugging for slow or troublesome queries, we might need extra information. Instead of polluting the codebase with multiple print statements, it’s a great idea to add the Marginalia gem by Basecamp. Now, this is how the query logs would look,

User Load (0.3ms)  SELECT `users`.* FROM `users`
WHERE `users`.`id` = 1234567890
LIMIT 1

/*application:saeloun,controller:users,action:show*/

In Rails 7

A recent PR to Rails brings Marginalia SQL comments to Rails as a native feature! It’s a much welcome change.

This PR allows for configurable tags that can be automatically added to all SQL queries generated by Active Record.

To turn this feature on, simply set a config option,

# config/application.rb

module Saeloun
  class Application < Rails::Application
     config.active_record.query_log_tags_enabled = true
  end
end

By default the application, controller and action details are added to the query tags:

class BlogsController < ApplicationController
  def index
    @blogs = Blog.all
  end
end
GET /blogs
# SELECT * FROM blogs /*application:Saeloun;controller:blogs;action:index*/

We can also configure our tags using procs.

Custom tags containing static values and procs can be defined in the application configuration:

config.active_record.query_log_tags = [
  :application,
  :controller,
  :action,
  {
    app_version: "1.3",
    current_user: -> { current_user.email }
  }
]

You can define both static values like app_version or dynamic values like current_user. Dynamic values are resolved with context inside the respective controller.

There are many more configurations possible, we suggest reading the PR before implementation!