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.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/application_insights/rack/track_request.rb', line 18

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

  @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

Instance Method Details

#call(env) ⇒ Object

Track requests and send data to Application Insights asynchronously.

Parameters:

  • env (Hash)

    the rack environment.



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
66
67
# File 'lib/application_insights/rack/track_request.rb', line 35

def call(env)
  # Build a request ID, incorporating one from our request if one exists.
  request_id = request_id_header(env['HTTP_REQUEST_ID'])
  env['ApplicationInsights.request.id'] = request_id

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

  start_time = start.iso8601(7)
  duration = format_request_duration(stop - start)
  success = status.to_i < 400

  request = ::Rack::Request.new env
  options = options_hash(request)

  data = request_data(request_id, start_time, duration, status, success, options)
  context = telemetry_context(request_id, env['HTTP_REQUEST_ID'])

  @client.channel.write data, context, start_time

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

  [status, headers, response]
end