Sorry this page looks weird. It was automatically migrated from my old blog, which had a different layout and different CSS.

Logging Subdomains in Rails 3

Rails 3.2 will have tagged logging so you can stamp your logs with subdomains (among other things). Until then you can use the Notifications API as follows.

In app/controllers/application_controller.rb:

# Put this before your other filters
before_filter :instrument_subdomain


def instrument_subdomain
  ActiveSupport::Notifications.instrument 'subdomain.action_controller', :subdomain => request.subdomain

In config/initializers/notifications.rb:

ActiveSupport::Notifications.subscribe 'subdomain.action_controller' do |name, start, finish, id, payload| "Subdomain: #{payload[:subdomain].presence || '[none]'}"

Now your logs will show each request’s subdomain. For example:

Started GET "/dashboard" for 123.456.42.153 at 2011-11-24 10:43:52 +0000
  Processing by DashboardsController#show as HTML
Subdomain: bigclient
Rendered dashboards/show.html.haml within layouts/account (15.4ms)
Completed 200 OK in 97ms (Views: 16.1ms | ActiveRecord: 32.3ms | Sphinx: 0.0ms)

This lets you see who’s doing what when you browse the logs.

In terms of bang for the buck, or utility per line of code, this was one of my better commits.

Andrew Stewart • 24 November 2011 • Rails
You can reach me by email or on Twitter.