Sha256: d06c92204341d0bf3e87c3824575f0df150c62161e7883e3217919d92b814547

Contents?: true

Size: 1.97 KB

Versions: 4

Compression:

Stored size: 1.97 KB

Contents

# -*- encoding : utf-8 -*-

require 'faraday'
require 'faraday_middleware'

module Ashikawa
  module Core
    # A more minimal logger as replacement for the very chatty Faraday logger
    class MinimalLogger < ::Faraday::Response::Middleware
      # The logger to be used
      #
      # @api public
      # @return [Logger] The configured logger
      attr_reader :logger

      # Should HTTP headers be logged
      #
      # @api public
      # @return [Boolean] If the headers will be logged or not. Defaults to `false`
      attr_reader :debug_headers

      # Initialize the middleware
      #
      # @api public
      # @param [Faraday::Middleware] app The middleware to nest this one in
      # @param [Logger] logger The logger to be used
      # @option options [Boolean] :debug_headers Should the headers be logged. Defaults to `false`
      def initialize(app, logger, options = {})
        super(app)
        @logger        = logger
        @debug_headers = options.fetch(:debug_headers) { false }
      end

      # Calls the this middleware and passes on to `super`
      #
      # @api public
      # @param [Faraday::Env] env The current env object
      def call(env)
        logger.debug('request') { "#{env.method.upcase} #{env.url}#{dump_headers(env.request_headers)}" }
        super
      end

      # The callback when the request was completed
      #
      # @api public
      # @param [Faraday::Env] env The current env object
      def on_complete(env)
        logger.debug('response') { "#{env.method.upcase} #{env.url} #{env.status}#{dump_headers(env.response_headers)}" }
      end

      private

      # Creates a one-liner out of headers
      #
      # @api private
      # @params [Hash] headers A headers hash
      def dump_headers(headers)
        " #{headers.map { |field_name, field_value| "#{field_name}: #{field_value.inspect}" }.join(' ')}" if debug_headers
      end
    end

    ::Faraday::Response.register_middleware minimal_logger: -> { MinimalLogger }
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ashikawa-core-0.14.0 lib/ashikawa-core/minimal_logger.rb
ashikawa-core-0.13.1 lib/ashikawa-core/minimal_logger.rb
ashikawa-core-0.13.0 lib/ashikawa-core/minimal_logger.rb
ashikawa-core-0.12.0 lib/ashikawa-core/minimal_logger.rb