AI, startup hacks, and engineering miracles from your friends at Faraday

Set application_name in ActiveRecord connections

Seamus Abshere on

Here's a great way to make Rails apps running on Postgres more inspectable.

Just put this in config/initializers/application_name.rb:

ActiveRecord::Base.connection.class.set_callback(:checkout, :after) { raw_connection.exec "set application_name = 'MyRailsApp'" }

Now when you inspect pg_stat_activity, you can tell which app is which.

psql# select
    application_name,
    state,
    pid,
    regexp_replace(query, '\s+', ' ', 'g') AS "query"
  from pg_stat_activity where not query ~ 'pg_stat_ac' ;
 application_name | state | pid |                                                                                                                                                               query
------------------+-------+-----+--------------------------------
                  | -     |  24 |
                  | -     |  22 |
 MyRailApp        | idle  | 111 |  SELECT a.attname, forma[...]
                  | -     |  20 |
                  | -     |  19 |
                  | -     |  21 |
(6 rows)

Thanks to this question on SO!