lib/shutl/resource/default_logger.rb in shutl_resource-1.8.0 vs lib/shutl/resource/default_logger.rb in shutl_resource-1.8.2

- old
+ new

@@ -1,10 +1,8 @@ require 'forwardable' -module Faraday - class Middleware - class DefaultLogger < Faraday::Middleware +class DefaultLogger < Faraday::Middleware extend Forwardable def_delegators :@logger, :debug, :info, :warn, :error, :fatal def initialize(app, options = {}) @@ -16,34 +14,34 @@ end def call(env) start_time = Time.now info request_info(env) - debug request_debug(env) + request_debug(env) @app.call(env).on_complete do end_time = Time.now response_time = end_time - start_time info response_info(env, response_time) - debug response_debug(env) + response_debug(env) end end private def request_info(env) - " Started %s request to: %s" % [ env[:method].to_s.upcase, env[:url] ] + "Started %s request to: %s" % [ env[:method].to_s.upcase, env[:url] ] end def response_info(env, response_time) - " Response from %s; Status: %d; Time: %.1fms" % [ env[:url], env[:status], (response_time * 1_000.0) ] + "Response from %s; Status: %d; Time: %.1fms" % [ env[:url], env[:status], (response_time * 1_000.0) ] end def request_debug(env) request_headers = obfuscate_auth env[:request_headers] - debug_message("Request", request_headers, env[:body]) + debug_request_response("Request", request_headers, env[:body]) end def obfuscate_auth(headers) headers.dup.tap do |h| if auth = h["Authorization"] @@ -52,27 +50,20 @@ end end end def response_debug(env) - debug_message("Response", env[:response_headers], env[:body]) + debug_request_response("Response", env[:response_headers], env[:body]) end - def debug_message(name, headers, body) - <<-MESSAGE.gsub(/^ +([^ ])/m, ' \\1') - #{name} Headers: - ---------------- - #{format_headers(headers)} - - #{name} Body: - ------------- - #{body} - MESSAGE + def debug_request_response(name, headers, body) + debug "#{name} headers: #{JSON.generate headers}" + debug "#{name} body: #{format_body body}" end - def format_headers(headers) - length = headers.map {|k,v| k.to_s.size }.max - headers.map { |name, value| " #{name.to_s.ljust(length)} : #{value}" }.join("\n") + def format_body(body) + return '' unless body + JSON.generate JSON.parse Array(body).join("\n") + rescue JSON::ParserError + Array(body).join("\n").gsub /\n/, '\n' end end - end -end