Sha256: 0e55ee4c5490f89581df1d0bddf68ae763fd5043708881efac463908a12d660a

Contents?: true

Size: 1.52 KB

Versions: 1

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true

require 'faraday/logging/formatter'

module ErpIntegration
  module Middleware
    class Logger < Faraday::Middleware
      # Notice that logging headers will expose sensitive information
      # like api-key.
      DEFAULT_OPTIONS = { headers: false, bodies: true, errors: true }.freeze

      def initialize(app, logger = nil, options = {})
        super(app)

        @logger = logger
        formatter_klass = options.delete(:formatter) || Faraday::Logging::Formatter
        @formatter = formatter_klass.new(logger: logger, options: DEFAULT_OPTIONS)
        yield @formatter if block_given?
      end

      def call(env)
        api_key_fragment = sanitize_api_key(env[:request_headers]['X-API-KEY'])

        if @logger.respond_to?(:tagged)
          @logger.tagged("API key *#{api_key_fragment}") do
            @formatter.request(env)

            @app.call(env).on_complete { |response| on_complete(response) }
          end
        else
          @logger.info("Requested ERP with API key *#{api_key_fragment}")
          @formatter.request(env)

          @app.call(env).on_complete { |response| on_complete(response) }
        end
      end

      def on_complete(env)
        @formatter.response(env)
      end

      def on_error(exc)
        @formatter.exception(exc) if @formatter.respond_to?(:exception)
      end

      # @param [String] api_key
      # @return [String] The last 4 characters of the API key
      def sanitize_api_key(api_key)
        api_key[-4..-1] if api_key
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
erp_integration-0.55.0 lib/erp_integration/middleware/logger.rb