Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 12th, 2012  |  syntax: None  |  size: 7.16 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Instrument Anything in Rails 3
  2. ==============================
  3.  
  4. With Rails 3.0 released a few weeks ago I've migrated a few apps and I'm constantly finding useful new improvements.  One such improvement is the ability to log anything in the same way that Rails internally logs ActiveRecord and ActionView.  By default Rails 3 logs look slightly spiffier than those produced by Rails 2.3: (notice the second line has been cleaned up)
  5.  
  6.     Started GET "/" for 127.0.0.1 at Mon Sep 06 01:07:11 -0400 2010
  7.       Processing by HomeController#index as HTML
  8.       User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE (`users`.`id` = 3) LIMIT 1
  9.       CACHE (0.0ms)  SELECT `users`.* FROM `users` WHERE (`users`.`id` = 3) LIMIT 1
  10.     Rendered layouts/_nav.html.erb (363.4ms)
  11.     Rendered layouts/_nav.html.erb (1.1ms)
  12.     Rendered layouts/_footer.html.erb (2.6ms)
  13.     Rendered home/index.html.erb within layouts/application (503.6ms)
  14.     Completed 200 OK in 510ms (Views: 507.9ms | ActiveRecord: 406.3ms)
  15.  
  16. This output format is very informative, but what if we're using MongoDB or CouchDB instead of ActiveRecord? What if our page has a Solr query that takes up a signification portion of the response time, and we want to break it out of the total?
  17.  
  18. The app I'm working on at Market.io uses Solr extensively via the [delsolr](http://delsolr.rubyforge.org/) gem.  Since delsolr is not Rails-specific, I have created a wrapper around the service calls to add hooks.  If I wanted to log Solr queries I could just add `Rails.logger.info "Solr query: #{query}"` but now Rails provides a better way.
  19.  
  20. In Rails 3, logging has been abstracted into [ActiveSupport::Notifications](http://rdoc.info/github/rails/rails/v3.0.0/ActiveSupport/Notifications), which publishes logging events, and [ActiveSupport::LogSubscriber](http://rdoc.info/github/rails/rails/v3.0.0/ActiveSupport/LogSubscriber), which consumes the events and logs the output.  This abstraction lets any number of entities publish notifications. (I'm calling those entities "services" for the purpose of this article, but any call can be instrumented.)
  21.  
  22. ActiveRecord provides an excellent example of how to subscribe to notifications.  I've adapted it to delsolr with minimal changes.  First we tell Rails what to instrument:
  23.  
  24.     class SolrDocument
  25.       def self.query(query_type, options={})
  26.         ActiveSupport::Notifications.instrument("query.delsolr",
  27.                                                 :query => options) do
  28.           ProductDocument.delsolr_client.query(query_type, options)
  29.         end
  30.       end
  31.     end
  32.  
  33. I've wrapped my client call in an ActiveSupport::Notifications block with the first argument in the format `{action}.{service}`.  The second argument is the "payload", a hash that gets passed to the log subscriber.  In order to catch the notification, we need to write a subscriber:
  34.  
  35.     module SolrInstrumentation
  36.       class LogSubscriber < ActiveSupport::LogSubscriber
  37.         def query(event)
  38.           return unless logger.debug?
  39.  
  40.           name = '%s (%.1fms)' % ["SOLR Query", event.duration]
  41.  
  42.           # produces: 'query: "foo" OR "bar", rows: 3, ...'
  43.           query = event.payload[:query].map{ |k, v| "#{k}: #{color(v, BOLD, true)}" }.join(', ')
  44.  
  45.           debug "  #{color(name, YELLOW, true)}  [ #{query} ]"
  46.         end
  47.       end
  48.     end
  49.  
  50. The subscriber will receive an event with a method `#payload` that returns the hash we passed in earlier with the `:duration` key added.  We simply construct a log line and then use `#debug` to output it to our logfile.  ActiveSupport::LogSubscriber comes with a `#color` method that makes highlighting output very easy.
  51.  
  52. Next, we need to register our subscriber to receive events.  We attach our LogSubscriber to all events in the `delsolr` namespace:
  53.  
  54.     SolrInstrumentation::LogSubscriber.attach_to :delsolr
  55.  
  56. The next step would be to instrument our other Solr calls such as `delete` and `commit` by wrapping the Solr calls with "delete.delsolr" and "commit.delsolr" and adding the appropriate methods.
  57.  
  58. Now we should have something like this in our Rails log:
  59.  
  60.     Started GET "/" for 127.0.0.1 at Mon Sep 06 01:07:11 -0400 2010
  61.       Processing by HomeController#index as HTML
  62.       User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE (`users`.`id` = 3) LIMIT 1
  63.       CACHE (0.0ms)  SELECT `users`.* FROM `users` WHERE (`users`.`id` = 3) LIMIT 1
  64.       SOLR Query (52.2ms)  [ rows: 25, query: "rails 3" OR "rails 2.3", start: 0, fields: * score, sort: created_at desc ]
  65.     Rendered layouts/_nav.html.erb (363.4ms)
  66.     Rendered layouts/_nav.html.erb (1.1ms)
  67.     Rendered layouts/_footer.html.erb (2.6ms)
  68.     Rendered home/index.html.erb within layouts/application (503.6ms)
  69.     Completed 200 OK in 562ms (Views: 507.9ms | ActiveRecord: 406.3ms)
  70.  
  71. Now it's easy to spot and debug the Solr queries, but it would be nice to see the breakout as well.  For that we need to extend our controllers.
  72.  
  73.     module SolrInstrumentation
  74.       module ControllerRuntime
  75.         extend ActiveSupport::Concern
  76.  
  77.         protected
  78.  
  79.         def append_info_to_payload(payload)
  80.           super
  81.           payload[:solr_runtime] = SolrInstrumentation::LogSubscriber.runtime
  82.         end
  83.  
  84.         module ClassMethods
  85.           def log_process_action(payload)
  86.             messages, solr_runtime = super, payload[:solr_runtime]
  87.             messages << ("Solr: %.1fms" % solr_runtime.to_f) if solr_runtime
  88.             messages
  89.           end
  90.         end
  91.       end
  92.     end
  93.  
  94.     ActiveSupport.on_load(:action_controller) do
  95.       include SolrInstrumentation::ControllerRuntime
  96.     end
  97.  
  98.  
  99. Notice that we no longer have to jump through the `self.included` hoops anymore; in Rails 3 we can extend ActiveSupport::Concern to easily add features to ActionController.  ActionController has instrumented the entire request in the same way that we instrumented our Solr call, so we just need to call our controller's `#append_info_to_payload` hook to inject our runtime info into the request notification event.  Lastly, we use the `#log_process_action` hook to catch the payload we just modified and generate a message, which should appear in the logs:
  100.  
  101.     Completed 200 OK in 562ms (Views: 507.9ms | ActiveRecord: 406.3ms | Solr: 52.2ms)
  102.  
  103. Solr normally shouldn't be called in the views, but if your service is used frequently in views and you don't want it to count towards the view's rendering time you can add a `#cleanup_view_runtime` method to the ControllerRuntime module to return the real view rendering time.  It involves a bit more work in calculating the service's runtime; check out the [source of ActiveRecord::LogSubscriber](http://github.com/rails/rails/blob/master/activerecord/lib/active_record/log_subscriber.rb) for an example.
  104.  
  105. Rails 3's notifications open up a lot of possibilities for both publishing and subscribing to events. Already Ilya Grigorik has taken advantage of this in his [Speed Tracer Rack middleware](http://www.igvita.com/2010/07/19/speed-tracer-server-side-tracing-with-rack/) by subscribing to timing events and outputting them to Google Chrome's [Speed Tracer](http://code.google.com/webtoolkit/speedtracer/) browser extension.  I imagine notifications will simplify NewRelic's monitoring gem as well.
  106.  
  107.  
  108. Thanks to Bryan Helmkamp ([@brynary](http://twitter.com/brynary)) for technical proofreading.