[Awesome Ruby Gem] Use marginalia gem to attach comments to your Rails ActiveRecord queries

marginalia

The marginalia gem attaching comments to your ActiveRecord queries. By default, it adds the application, controller, and action names as a comment at the end of each query.

This helps when searching log files for queries, and seeing where slow queries came from.

For example, once enabled, your logs will look like:

1
2
3
4
Account Load (0.3ms)  SELECT `accounts`.* FROM `accounts` 
WHERE `accounts`.`queenbee_id` = 1234567890
LIMIT 1
/*application:BCX,controller:project_imports,action:show*/

Installation

You can install it as a gem:

1
$ gem install marginalia

or add it into a Gemfile (Bundler):

1
2
3
4
5
# Gemfile

# basecamp/marginalia: Attach comments to ActiveRecord's SQL queries
# https://github.com/basecamp/marginalia
gem 'marginalia', '1.9.0', :require => false

Then, run bundle install.

1
$ bundle install

Configuration

Marginalia ships with :application, :controller, and :action enabled by default. In addition, implementation is provided for:

  • :line (for file and line number calling query). :line supports a configuration by setting a regexp in Marginalia::Comment.lines_to_ignore to exclude parts of the stacktrace from inclusion in the line comment.
  • :controller_with_namespace to include the full classname (including namespace) of the controller.
  • :job to include the classname of the ActiveJob being performed.
  • :hostname to include Socket.gethostname.
  • :pid to include current process id.
  • :db_host to include the configured database hostname.
  • :socket to include the configured database socket.
  • :database to include the configured database name.
1
2
3
4
5
# config/initializers/marginalia.rb

# basecamp/marginalia: Attach comments to ActiveRecord's SQL queries
# https://github.com/basecamp/marginalia
Marginalia::Comment.components = [:application, :controller, :action, :line, :controller_with_namespace, :job]

References

[1] basecamp/marginalia: Attach comments to ActiveRecord’s SQL queries - https://github.com/basecamp/marginalia

[2] pt-query-digest - https://www.percona.com/doc/percona-toolkit/2.1/pt-query-digest.html#query-reviews