Class: OpenCensus::Trace::Integrations::RackMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/opencensus/trace/integrations/rack_middleware.rb

Overview

Rack integration

This is a middleware for Rack applications:

  • It wraps all incoming requests in a root span
  • It exports the captured spans at the end of the request.

Example:

require "opencensus/trace/integrations/rack_middleware"

use OpenCensus::Trace::Integrations::RackMiddleware

Instance Method Summary collapse

Constructor Details

#initialize(app, exporter: nil) ⇒ RackMiddleware

Create the Rack middleware.

Parameters:

  • app (#call)

    Next item on the middleware stack

  • exporter (#export) (defaults to: nil)

    The exported used to export captured spans at the end of the request. Optional: If omitted, uses the exporter in the current config.


55
56
57
58
# File 'lib/opencensus/trace/integrations/rack_middleware.rb', line 55

def initialize app, exporter: nil
  @app = app
  @exporter = exporter || OpenCensus::Trace.config.exporter
end

Instance Method Details

#call(env) ⇒ Array

Run the Rack middleware.

Parameters:

  • env (Hash)

    The rack environment

Returns:

  • (Array)

    The rack response. An array with 3 elements: the HTTP response code, a Hash of the response headers, and the response body which must respond to each.


68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/opencensus/trace/integrations/rack_middleware.rb', line 68

def call env
  formatter = AUTODETECTABLE_FORMATTERS.detect do |f|
    env.key? f.rack_header_name
  end
  if formatter
    context = formatter.deserialize env[formatter.rack_header_name]
  end

  Trace.start_request_trace \
    trace_context: context,
    same_process_as_parent: false do |span_context|
    begin
      Trace.in_span get_path(env) do |span|
        start_request span, env
        @app.call(env).tap do |response|
          finish_request span, response
        end
      end
    ensure
      @exporter.export span_context.build_contained_spans
    end
  end
end