instrumenter.rb 2.1 KB
Newer Older
R
Rafael Mendonça França 已提交
1 2
require 'securerandom'

3 4
module ActiveSupport
  module Notifications
A
Akira Matsuda 已提交
5
    # Instrumenters are stored in a thread local.
6
    class Instrumenter
7 8
      attr_reader :id

9
      def initialize(notifier)
10
        @id       = unique_id
11 12 13
        @notifier = notifier
      end

14
      # Instrument the given block by measuring the time taken to execute it
15
      # and publish it. Notice that events get sent even if an error occurs
16
      # in the passed-in block.
J
José Valim 已提交
17
      def instrument(name, payload={})
18
        start name, payload
19
        begin
20
          yield payload
21 22 23
        rescue Exception => e
          payload[:exception] = [e.class.name, e.message]
          raise e
24
        ensure
25
          finish name, payload
26
        end
27 28
      end

29 30 31 32 33 34 35 36 37 38
      # Send a start notification with +name+ and +payload+.
      def start(name, payload)
        @notifier.start name, @id, payload
      end

      # Send a finish notification with +name+ and +payload+.
      def finish(name, payload)
        @notifier.finish name, @id, payload
      end

39
      private
40 41 42 43

      def unique_id
        SecureRandom.hex(10)
      end
44 45 46
    end

    class Event
47 48
      attr_reader :name, :time, :transaction_id, :payload, :children
      attr_accessor :end
49

50
      def initialize(name, start, ending, transaction_id, payload)
51 52 53 54 55
        @name           = name
        @payload        = payload.dup
        @time           = start
        @transaction_id = transaction_id
        @end            = ending
56
        @children       = []
57
        @duration       = nil
58 59
      end

60 61
      # Returns the difference in milliseconds between when the execution of the
      # event started and when it ended.
62 63 64 65 66 67 68 69 70
      #
      #   ActiveSupport::Notifications.subscribe('wait') do |*args|
      #     @event = ActiveSupport::Notifications::Event.new(*args)
      #   end
      #
      #   ActiveSupport::Notifications.instrument('wait') do
      #     sleep 1
      #   end
      #
C
claudiob 已提交
71
      #   @event.duration # => 1000.138
72
      def duration
73
        @duration ||= 1000.0 * (self.end - time)
74 75 76 77
      end

      def <<(event)
        @children << event
78 79 80
      end

      def parent_of?(event)
81
        @children.include? event
82 83 84 85
      end
    end
  end
end