Sha256: e87958b72df6c0f8932526d322e3d974eaf8a53b5750cf24d6c6357289c14ce3

Contents?: true

Size: 1.36 KB

Versions: 15

Compression:

Stored size: 1.36 KB

Contents

# frozen_string_literal: true

module HTTP
  module Features
    # Log requests and responses. Request verb and uri, and Response status are
    # logged at `info`, and the headers and bodies of both are logged at
    # `debug`. Be sure to specify the logger when enabling the feature:
    #
    #    HTTP.use(logging: {logger: Logger.new(STDOUT)}).get("https://example.com/")
    #
    class Logging < Feature
      HTTP::Options.register_feature(:logging, self)

      class NullLogger
        %w[fatal error warn info debug].each do |level|
          define_method(level.to_sym) do |*_args|
            nil
          end

          define_method(:"#{level}?") do
            true
          end
        end
      end

      attr_reader :logger

      def initialize(logger: NullLogger.new)
        @logger = logger
      end

      def wrap_request(request)
        logger.info { "> #{request.verb.to_s.upcase} #{request.uri}" }
        logger.debug { "#{stringify_headers(request.headers)}\n\n#{request.body.source}" }

        request
      end

      def wrap_response(response)
        logger.info { "< #{response.status}" }
        logger.debug { "#{stringify_headers(response.headers)}\n\n#{response.body}" }

        response
      end

      private

      def stringify_headers(headers)
        headers.map { |name, value| "#{name}: #{value}" }.join("\n")
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 3 rubygems

Version Path
direct7-0.0.18 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/features/logging.rb
direct7-0.0.17 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/features/logging.rb
direct7-0.0.16 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/features/logging.rb
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/http-5.2.0/lib/http/features/logging.rb
direct7-0.0.13 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/features/logging.rb
direct7-0.0.12 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/features/logging.rb
http-5.2.0 lib/http/features/logging.rb
direct7-0.0.11 vendor/bundle/ruby/2.7.0/gems/http-5.1.1/lib/http/features/logging.rb
http-5.1.1 lib/http/features/logging.rb
http-5.1.0 lib/http/features/logging.rb
http-5.0.4 lib/http/features/logging.rb
http-5.0.3 lib/http/features/logging.rb
http-5.0.2 lib/http/features/logging.rb
http-5.0.1 lib/http/features/logging.rb
http-5.0.0 lib/http/features/logging.rb