Skip to content

Instantly share code, notes, and snippets.

@FooBarWidget
Created October 26, 2018 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FooBarWidget/a9626c49e589b369659e53b54934b8ed to your computer and use it in GitHub Desktop.
Save FooBarWidget/a9626c49e589b369659e53b54934b8ed to your computer and use it in GitHub Desktop.
class DebugMiddleware
def initialize(app, message)
@app = app
@message = message
end
def call(*args)
STDERR.puts "BEGIN #{request_id} -- #{@message}"
status, headers, body = @app.call(*args)
consumed_body = consume_body(body)
[status, headers, consumed_body]
ensure
STDERR.puts "END #{request_id} -- #{@message} | status = #{status}, body size = #{get_body_size(consumed_body)}"
end
private
def request_id
Thread.current[:name] || Thread.current.object_id.to_s(36)
end
def consume_body(body)
return nil if body.nil?
return [body] if body.is_a?(String)
begin
result = []
body.each do |part|
result << part
end
result
ensure
body.close if body.respond_to?(:close)
end
end
def get_body_size(consumed_body)
return 'nil' if consumed_body.nil?
result = 0
consumed_body.each { |part| result += part.bytesize }
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment