2012-06-19 16:04:07 -04:00
|
|
|
require 'securerandom'
|
|
|
|
|
2009-11-28 15:49:07 -05:00
|
|
|
module ActiveSupport
|
|
|
|
module Notifications
|
2012-03-21 16:06:56 -04:00
|
|
|
# Instrumentors are stored in a thread local.
|
2009-11-28 15:49:07 -05:00
|
|
|
class Instrumenter
|
2010-01-04 16:22:21 -05:00
|
|
|
attr_reader :id
|
|
|
|
|
2009-11-28 15:49:07 -05:00
|
|
|
def initialize(notifier)
|
|
|
|
@id = unique_id
|
|
|
|
@notifier = notifier
|
|
|
|
end
|
|
|
|
|
2010-01-13 16:28:18 -05:00
|
|
|
# Instrument the given block by measuring the time taken to execute it
|
2010-05-02 16:40:20 -04:00
|
|
|
# and publish it. Notice that events get sent even if an error occurs
|
|
|
|
# in the passed-in block
|
2010-07-25 14:46:42 -04:00
|
|
|
def instrument(name, payload={})
|
2012-03-21 16:06:56 -04:00
|
|
|
@notifier.start(name, @id, payload)
|
2010-04-27 17:13:47 -04:00
|
|
|
begin
|
2010-07-21 19:29:26 -04:00
|
|
|
yield
|
2010-05-02 16:40:20 -04:00
|
|
|
rescue Exception => e
|
|
|
|
payload[:exception] = [e.class.name, e.message]
|
|
|
|
raise e
|
2010-04-27 17:13:47 -04:00
|
|
|
ensure
|
2012-03-21 16:06:56 -04:00
|
|
|
@notifier.finish(name, @id, payload)
|
2010-04-27 17:13:47 -04:00
|
|
|
end
|
2009-11-28 15:49:07 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def unique_id
|
|
|
|
SecureRandom.hex(10)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class Event
|
2012-06-18 19:34:23 -04:00
|
|
|
attr_reader :name, :time, :transaction_id, :payload, :children
|
|
|
|
attr_accessor :end
|
2009-11-28 15:49:07 -05:00
|
|
|
|
2009-12-26 14:28:53 -05:00
|
|
|
def initialize(name, start, ending, transaction_id, payload)
|
2009-11-28 15:49:07 -05:00
|
|
|
@name = name
|
|
|
|
@payload = payload.dup
|
|
|
|
@time = start
|
|
|
|
@transaction_id = transaction_id
|
|
|
|
@end = ending
|
2012-06-18 19:34:23 -04:00
|
|
|
@children = []
|
|
|
|
end
|
|
|
|
|
|
|
|
def duration
|
|
|
|
1000.0 * (self.end - time)
|
|
|
|
end
|
|
|
|
|
|
|
|
def <<(event)
|
|
|
|
@children << event
|
2009-11-28 15:49:07 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def parent_of?(event)
|
2012-06-18 19:34:23 -04:00
|
|
|
@children.include? event
|
2009-11-28 15:49:07 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|