I don't think there's a native way to do this in Faraday, but it'd be easy to implement in middleware:
require 'faraday'
class LogOnError < Faraday::Response::Middleware
extend Forwardable
def_delegators :@logger, :debug, :info, :warn, :error, :fatal
ClientErrorStatuses = 400...600
def initialize(app, options = {})
@app = app
@logger = options.fetch(:logger) {
require 'logger'
::Logger.new($stdout)
}
end
def call(env)
@app.call(env).on_complete do
case env[:status]
when ClientErrorStatuses
info "#{env.method} #{env.url.to_s} #{response_values(env)}"
end
end
end
def response_values(env)
{:status => env.status, :headers => env.response_headers, :body => env.body}
end
end
conn = Faraday.new('https://github.com/') do |c|
c.use LogOnError
c.use Faraday::Adapter::NetHttp
end
puts "No text to stdout"
response = conn.get '/' #=> No text to stdout]
puts "No text above..."
puts "Text to stdout:"
response = conn.get '/cant-find-me' #=> Text to standoupt
Which produces:
No text to stdout
No text above...
Text to stdout:
I, [2014-09-17T14:03:36.383722 #18881] INFO -- : get https://github.com/cant-find-me {:status=>404, :headers=>{"server"=>"GitHub.com", "date"=>"Wed, 17 Sep 2014 13:03:36 GMT", "content-type"=>"application/json; charset=utf-8", "transfer-encoding"=>"chunked", "connection"=>"close", "status"=>"404 Not Found", "x-xss-protection"=>"1; mode=block", "x-frame-options"=>"deny", "content-security-policy"=>"default-src *; script-src assets-cdn.github.com www.google-analytics.com collector-cdn.github.com; object-src assets-cdn.github.com; style-src 'self' 'unsafe-inline' 'unsafe-eval' assets-cdn.github.com; img-src 'self' data: assets-cdn.github.com identicons.github.com www.google-analytics.com collector.githubapp.com *.githubusercontent.com *.gravatar.com *.wp.com; media-src 'none'; frame-src 'self' render.githubusercontent.com gist.github.com www.youtube.com player.vimeo.com checkout.paypal.com; font-src assets-cdn.github.com; connect-src 'self' ghconduit.com:25035 live.github.com uploads.github.com s3.amazonaws.com", "vary"=>"X-PJAX", "cache-control"=>"no-cache", "x-ua-compatible"=>"IE=Edge,chrome=1", "set-cookie"=>"logged_in=no; domain=.github.com; path=/; expires=Sun, 17-Sep-2034 13:03:36 GMT; secure; HttpOnly", "x-runtime"=>"0.004330", "x-github-request-id"=>"2EED8226:76F6:1951EDA:541986A8", "strict-transport-security"=>"max-age=31536000; includeSubdomains; preload", "x-content-type-options"=>"nosniff"}, :body=>"{\"error\":\"Not Found\"}"}
You can split this off into it's own class that you include
to clean it up a bit.