Sha256: 5f2737461821d0190ca859fbc96b57b6a9c929ea9928d49060980af7c399979a

Contents?: true

Size: 1.79 KB

Versions: 5

Compression:

Stored size: 1.79 KB

Contents

module Net

  class HTTP

    private

    HIDDEN_PORTS = [ 80, 443 ].freeze

    public

    def connect_with_logging
      HttpEventLogger::Event::Connection.new(@address, @port) unless started?
      connect_without_logging
    end

    alias_method_chain :connect, :logging

    def request_with_logging(req, body = nil, &block)
      create_request_event(req, body) if started?
      response = nil
      time_taken_in_seconds = ::Benchmark.realtime do
        response = request_without_logging(req, body, &block)
      end
      create_response_event(time_taken_in_seconds, response) if started?
      response
    end

    alias_method_chain :request, :logging

    private

    def create_request_event(req, body)
      @request_event = HttpEventLogger::Event::Request.new(
        method:  req.method,
        uri:     absolute_url_from(req),
        headers: req.each_header.collect,
        body:    request_body_from(req, body)
      )
    end

    def absolute_url_from(req)
      protocol       = @use_ssl ? "https" : "http"
      port_indicator = HIDDEN_PORTS.include?(@port) ? "" : ":#{@port}"
      hostname       = "#{@address}#{port_indicator}"
      "#{protocol}://#{hostname}#{req.path}"
    end

    # A bit convoluted because post_form uses form_data= to assign the data, so in that case req.body will be empty
    def request_body_from(req, body)
      req.body.nil? || req.body.size == 0 ? body : req.body
    end

    def create_response_event(time_taken_in_seconds, response)
      HttpEventLogger::Event::Response.new(
        request:               @request_event,
        time_taken_in_seconds: time_taken_in_seconds,
        status:                response.code,
        headers:               response.each_header.collect,
        body:                  response.body
      )
    end

  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
http_event_logger-0.1.0 ./lib/http_event_logger/adapter/net_http.rb
http_event_logger-0.1.0.rc4 ./lib/http_event_logger/adapter/net_http.rb
http_event_logger-0.1.0.rc3 ./lib/http_event_logger/adapter/net_http.rb
http_event_logger-0.1.0.rc2 ./lib/http_event_logger/adapter/net_http.rb
http_event_logger-0.1.0.rc1 ./lib/http_event_logger/adapter/net_http.rb