Sha256: c9161afa9a55de2c883a08395cbd7db6dca30db59947285767a0cfdef340b957

Contents?: true

Size: 1.02 KB

Versions: 3

Compression:

Stored size: 1.02 KB

Contents

module ServiceTemplate
  class Middleware
    class RequestStats
      def initialize(app)
        @app = app
      end

      def normalize_path(path)
        case
          when path == '/'
            'root'
          else
            path.start_with?('/') ? path[1..-1] : path
        end
      end

      def call(env)
        # Mark the request time
        start = Time.now

        # Process the request
        status, headers, body = @app.call(env)

        # Mark the response time
        stop = Time.now

        # Calculate total response time
        response_time = (stop - start) * 1000

        request = Rack::Request.new(env)
        path = normalize_path(request.path_info)

        # Emit stats to StatsD
        ServiceTemplate::Stats.emitter.timing('response_time', response_time)
        ServiceTemplate::Stats.emitter.timing("path.#{ServiceTemplate::Stats.path_to_key(request.request_method, path)}.response_time", response_time)

        # Return the results
        [status, headers, body]
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
service_template-0.5.2 lib/service_template/middleware/request_stats.rb
service_template-0.5.1 lib/service_template/middleware/request_stats.rb
service_template-0.5.0 lib/service_template/middleware/request_stats.rb