module PriceHubble
module Instrumentation
class LogSubscriber < ActiveSupport::LogSubscriber
def logger
return unless PriceHubble.configuration.request_logging
PriceHubble.configuration.logger
end
def request(event)
log_action_summary(event)
log_request_details(event)
log_response_details(event)
end
private
def log_action_summary(event)
env = event.payload
info do
"[#{req_id(env)}] #{req_origin(env)} -> #{res_result(env)} " \
"(#{event.duration.round(1)}ms)"
end
end
def log_request_details(event)
env = event.payload
debug do
"[#{req_id(env)}] #{req_dest(env)} > " \
"#{env..sort.to_h.to_json}"
end
end
def log_response_details(event)
env = event.payload
if env.response.nil?
return error do
"[#{req_id(env)}] #{req_dest(env)} < #{res_result(env)}"
end
end
debug do
"[#{req_id(env)}] #{req_dest(env)} < " \
"#{env..sort.to_h.to_json}"
end
end
def req_id(env)
env.request.context[:request_id].to_s
end
def req_origin(env)
req = env.request.context
action = req[:action]
action = color(action, color_method(action), true)
client = req[:client].to_s.gsub('PriceHubble::Client', 'PriceHubble')
"#{client.underscore}##{action}"
end
def req_dest(env)
method = env[:method].to_s.upcase
method = color(method, color_method(method), true)
url = env[:url].to_s.gsub(/access_token=[^&]+/,
'access_token=[FILTERED]')
"#{method} #{url}"
end
def res_result(env)
return color('no response', RED, true).to_s if env.response.nil?
status = env[:status]
color("#{status}/#{env[:reason_phrase]}", color_status(status), true)
end
def color_status(status)
case status
when 0..199 then MAGENTA
when 200..299 then GREEN
when 300..399 then YELLOW
when 400..599 then RED
else WHITE
end
end
def color_method(method)
case method
when /delete/i then RED
when /get|search|reload|find/i then BLUE
when /post|create/i then GREEN
when /put|patch|update/i then YELLOW
when /login|logout|download|query/i then CYAN
else MAGENTA
end
end
end
end
end