Sha256: 8923b2ac38594494b5536e2e9850f08e05c5cb4685bd421cb0dc78deeeba6da1

Contents?: true

Size: 1.78 KB

Versions: 1

Compression:

Stored size: 1.78 KB

Contents

##############################################################################
#                             Faraday Plugin
##############################################################################

begin
  require 'faraday/response'

  module  Rspeckled
  module  Faraday
  module  Middleware
  class   DetailedLogger < ::Faraday::Response::Middleware
    def self.default_logger
      require 'logger'

      ::Logger.new(STDOUT)
    end

    # :reek:ControlParameter
    def initialize(app, logger = nil, program_name = nil)
      super(app)

      @logger       = logger || self.class.default_logger
      @program_name = program_name
    end

    def call(env)
      @logger.info(@program_name) { curl_output('request', "#{env[:method].upcase} #{env[:url]}", env[:request_headers], env[:body]) }

      super
    end

    def on_complete(env)
      @logger.info(@program_name) { curl_output('response', "HTTP #{env[:status]}", env[:response_headers], env[:body]) }
    end

    private

    # :reek:ControlParameter
    # :reek:UtilityFunction
    def curl_output(direction, summary, headers, body)
      directional_arrow = direction == 'request' ? '>' : '<'
      color_code        = direction == 'request' ? 32 : 33

      curl_formatted_headers = headers.map { |name, value|
        colorize("#{directional_arrow} #{name}: #{value}", color_code)
      }.join("\n")

      [
        '',
        colorize("#{directional_arrow} #{summary}", color_code),
        curl_formatted_headers,
        '',
        colorize(body, 37),
      ].join("\n")
    end

    def colorize(string, color_code)
      "\e[#{color_code}m#{string}\e[0m"
    end
  end
  end
  end
  end

  ::Faraday::Response.register_middleware(:detailed_logger => Rspeckled::Faraday::Middleware::DetailedLogger)
rescue LoadError
  puts 'fara'
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rspeckled-0.0.11 lib/rspeckled/plugins/faraday.rb