class Fbe::Middleware::Formatter

License
MIT
Copyright
Copyright © 2024-2025 Zerocracy
Author

Yegor Bugayenko (yegor256@gmail.com)
Faraday logging formatter show verbose log for only error response

def dump_headers(headers)

def dump_headers(headers)
  return '' if headers.nil?
  headers.map { |k, v| "#{k}: #{v.inspect}" }.join("\n")
end

def request(http)

Parameters:
  • http (Hash) -- The hash with data about HTTP request
def request(http)
  @req = http
end

def response(http)

Parameters:
  • http (Hash) -- The hash with data about HTTP response
def response(http)
  return if http.status < 400
  if http.status == 403 && http.response_headers['content-type'].start_with?('application/json')
    warn(
      [
        "#{@req.method.upcase} #{apply_filters(@req.url.to_s)}",
        '->',
        http.status,
        '/',
        JSON.parse(http.response_body)['message']
      ].join(' ')
    )
    return
  end
  error(
    [
      "#{@req.method.upcase} #{apply_filters(@req.url.to_s)} HTTP/1.1",
      shifted(apply_filters(dump_headers(@req.request_headers))),
      '',
      shifted(apply_filters(@req.request_body)),
      "HTTP/1.1 #{http.status}",
      shifted(apply_filters(dump_headers(http.response_headers))),
      '',
      shifted(apply_filters(http.response_body))
    ].join("\n")
  )
end

def shifted(txt)

def shifted(txt)
  return '' if txt.nil?
  "  #{txt.gsub("\n", "\n  ")}"
end