Sha256: e4e0dd7ad8f27e816c312c782d30a39d50c8b049d593b36f1383e5075e830b88

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 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']) || 'none'
        request_uuid = SecureRandom.uuid

        @logger.with_tags(api_key_tag(api_key_fragment), request_uuid) do
          @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

      def api_key_tag(api_key_fragment)
        "API key *#{api_key_fragment}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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