Created
June 2, 2014 07:03
-
-
Save vasanthela/7afb8916c662ba783041 to your computer and use it in GitHub Desktop.
Faraday Middleware to log request bodies.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Custom Faraday Middleware to log request bodies | |
# | |
# Code borrowed from https://github.com/lostisland/faraday/pull/277 | |
# Once the pull request gets merged, this middleware is unnecessary. | |
# | |
# Default option is to not print request bodies | |
# | |
# Example usage: | |
# | |
# # Defaults logger | |
# Faraday.new() do |conn| | |
# conn.use LogRequestBodies, nil, { :bodies => true } | |
# end | |
# | |
# # Custom logger | |
# Faraday.new() do |conn| | |
# conn.use LogRequestBodies, custom_logger, { :bodies => true } | |
# end | |
# | |
class LogRequestBodies < Faraday::Response::Middleware | |
extend Forwardable | |
DEFAULT_OPTIONS = { :bodies => false } | |
def initialize(app, logger = nil, options = {}) | |
super(app) | |
@logger = logger || begin | |
require 'logger' | |
::Logger.new(STDOUT) | |
end | |
@options = DEFAULT_OPTIONS.merge(options) | |
end | |
def_delegators :@logger, :debug, :info, :warn, :error, :fatal | |
def call(env) | |
debug('request') { dump_body(env[:body]) } if env[:body] && log_body?(:request) | |
@app.call(env).on_complete do |env| | |
debug('response') { dump_body env[:body] } if env[:body] && log_body?(:response) | |
end | |
end | |
def dump_body(body) | |
if body.respond_to?(:to_str) | |
body.to_str | |
else | |
pretty_inspect(body) | |
end | |
end | |
def pretty_inspect(body) | |
require 'pp' unless body.respond_to?(:pretty_inspect) | |
body.pretty_inspect | |
end | |
def log_body?(type) | |
case @options[:bodies] | |
when Hash then @options[:bodies][type] | |
else @options[:bodies] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment