Module: Metrica::MethodInstrumentation

Defined in:
lib/metrica/method_instrumentation.rb

Overview

A utility module that can be used to add measuring capabilities to a class. Marking a method with instrument_method wraps it in a com.codahale.metrics.Timer.

Examples:

Adding instrumentation to a method.

class MyClass
  extend MethodInstrumentation
  def foo(a, b)
    ...
  end
  instrument_method :foo, 'myapp.foo'
end

See Also:

Instance Method Summary collapse

Instance Method Details

#instrument_method(method_name, metric_name, options = {}) ⇒ Object

Decorates the method with a timer that can be used for benchmarking.

Parameters:

  • method_name (Symbol)

    The name of the method.

  • metric_name (String)

    The name of the metric.

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :within_transaction (Boolean) — default: false

    Measure only when a web transaction is active.


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/metrica/method_instrumentation.rb', line 23

def instrument_method(method_name, metric_name, options = {})
  within_transaction = options[:within_transaction]
  timer_name = "_metrica_#{method_name}_timer"
  uninstrumented_method = "#{method_name}_without_instrumentation"

  alias_method uninstrumented_method, method_name
  if within_transaction
    class_eval <<-RUBY, __FILE__, __LINE__
        @@#{timer_name} = Metrica.timer("#{metric_name}")
        def #{method_name}(*args, &block)
          if Metrica::Transaction.active?
            @@#{timer_name}.measure do
              #{uninstrumented_method}(*args, &block)
            end
          else
            #{uninstrumented_method}(*args, &block)
          end
        end
    RUBY
  else
    class_eval <<-RUBY, __FILE__, __LINE__
        @@#{timer_name} = Metrica.timer("#{metric_name}")
        def #{method_name}(*args, &block)
          @@#{timer_name}.measure do
            #{uninstrumented_method}(*args, &block)
          end
        end
    RUBY
  end
end