Class: ApplicationInsights::Rack::TrackRequest

Inherits:
Object
  • Object
show all
Defined in:
lib/application_insights/rack/track_request.rb

Overview

Track every request and sends the request data to Application Insights.

Instance Method Summary collapse

Constructor Details

#initialize(app, instrumentation_key, buffer_size = 500, send_interval = 60) ⇒ TrackRequest

Initializes a new instance of the class.

Parameters:

  • app (Object)

    the inner rack application.

  • instrumentation_key (String)

    to identify which Application Insights application this data is for.

  • buffer_size (Fixnum) (defaults to: 500)

    the buffer size and the buffered requests would send to Application Insights when buffer is full.

  • send_interval (Fixnum) (defaults to: 60)

    the frequency (in seconds) to check buffer and send buffered requests to Application Insights if any.



17
18
19
20
21
22
# File 'lib/application_insights/rack/track_request.rb', line 17

def initialize(app, instrumentation_key, buffer_size = 500, send_interval = 60)
  @app = app
  @instrumentation_key = instrumentation_key
  @buffer_size = buffer_size
  @send_interval = send_interval
end

Instance Method Details

#call(env) ⇒ Object

Track requests and send data to Application Insights asynchronously.

Parameters:

  • env (Hash)

    the rack environment.



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
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/application_insights/rack/track_request.rb', line 26

def call(env)
  start = Time.now
  begin
    status, headers, response = @app.call(env)
  rescue Exception => ex
    status = 500
    exception = ex
  end
  stop = Time.now

  unless @client
    sender = @sender || Channel::AsynchronousSender.new
    sender.send_interval = @send_interval
    queue = Channel::AsynchronousQueue.new sender
    queue.max_queue_length = @buffer_size
    channel = Channel::TelemetryChannel.new nil, queue

    @client = TelemetryClient.new @instrumentation_key, channel
  end

  request = ::Rack::Request.new env
  id = rand(16**32).to_s(16)
  start_time = start.iso8601(7)
  duration = format_request_duration(stop - start)
  success = status.to_i < 400
  options = {
    :name => "#{request.request_method} #{request.path}",
    :http_method => request.request_method,
    :url => request.url
  }

  @client.track_request id, start_time, duration, status, success, options

  if exception
    @client.track_exception exception, handled_at: 'Unhandled'
    raise exception
  end

  [status, headers, response]
end