ActiveSupport::Notifications for Metrics

Posted on 14 Nov 2012 by Eric Oestrich

The other week I had to speed up an end point of an API I’m working on, and since I wanted to do it right I used metrics. A coworker pointed me on to ActiveSupport::Notification.instrument previously so I gave it a go here.

I ended up creating a module that you can include into a class which will instrument every method. I don’t think it’s the nicest code ever but it was handy in getting a somewhat large class set up quickly.

It’s available in this gist, but I’ve also included it below.

module Notifications
  extend ActiveSupport::Concern

  module ClassMethods
    def method_added(method_name)
      @methods ||= []
      return if @methods.include?(method_name) || method_name =~ /_old$/
      @methods << method_name

      class_eval %{alias #{method_name}_old #{method_name}}

      define_method(method_name) do |*args|
        instrument_name = "#{method_name}.#{}"
        ActiveSupport::Notifications.instrument(instrument_name) do
          send("#{method_name}_old", *args)

You also need to set up something that will log the instruments so you can see them.

ActiveSupport::Notifications.subscribe(/my_class$/) do |*args|
  event =*args)

  Rails.logger.warn "%7.2fms %s" % [event.duration,]


  1. ActiveSupport::Notifications
comments powered by Disqus
Creative Commons License
This site's content is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License unless otherwise specified. Code on this site is licensed under the MIT License unless otherwise specified.