Skip to content

Commit

Permalink
Added initial logging support.
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasuyezu committed Oct 7, 2013
1 parent 9d0c4f5 commit e885c18
Show file tree
Hide file tree
Showing 10 changed files with 195 additions and 1 deletion.
13 changes: 13 additions & 0 deletions lib/httparty.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
require 'httparty/net_digest_auth'
require 'httparty/version'
require 'httparty/connection_adapter'
require 'httparty/logger/logger'

# @see HTTParty::ClassMethods
module HTTParty
Expand Down Expand Up @@ -70,6 +71,18 @@ module ClassMethods

extend AllowedFormatsDeprecation

# Turns on logging
#
# class Foo
# include HTTParty
# logger Logger.new('http_logger'), :info, :apache
# end
def logger(logger, level=:info, format=:apache)
default_options[:logger] = logger
default_options[:log_level] = level
default_options[:log_format] = format
end

# Allows setting http proxy information to be used
#
# class Foo
Expand Down
27 changes: 27 additions & 0 deletions lib/httparty/logger/apache_logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module HTTParty
module Logger
class ApacheLogger #:nodoc:
TAG_NAME = HTTParty.name

attr_accessor :level, :logger, :current_time

def initialize(logger, level)
@logger = logger
@level = level.to_sym
end

def format(request, response)
@current_time ||= Time.new.strftime("%Y-%m-%d %H:%M:%S.%L %z")
http_method = request.http_method.name.split("::").last.upcase
path = request.path.to_s
content_length = response['Content-Length']

print(response.code, content_length, http_method, path)
end

def print(code, content_length, http_method, path)
@logger.send @level, "[#{TAG_NAME}] [#{@current_time}] #{code} \"#{http_method} #{path}\" #{content_length || "-"} "
end
end
end
end
52 changes: 52 additions & 0 deletions lib/httparty/logger/curl_logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
module HTTParty
module Logger
class CurlLogger #:nodoc:
TAG_NAME = HTTParty.name

attr_accessor :level, :logger, :current_time

def initialize(logger, level)
@logger = logger
@level = level.to_sym
end

def format(request, response)
@messages = []
@current_time ||= Time.new.strftime("%Y-%m-%d %H:%M:%S.%L %z")
http_method = request.http_method.name.split("::").last.upcase
path = request.path.to_s

print_outgoing "#{http_method} #{path}"
if request.options[:headers] && request.options[:headers].size > 0
request.options[:headers].each do |k, v|
print_outgoing "#{k}: #{v}"
end
end

print_outgoing ""
print_incoming "HTTP/#{response.http_version} #{response.code}"

headers = response.respond_to?(:headers) ? response.headers : response
response.each_header do |response_header|
print_incoming "#{response_header.capitalize}: #{headers[response_header]}"
end

print_incoming "\n#{response.body}"

@logger.send @level, @messages.join("\n")
end

def print_outgoing(line)
@messages << print(">", line)
end

def print_incoming(line)
@messages << print("<", line)
end

def print(direction, line)
"[#{TAG_NAME}] [#{@current_time}] #{direction} #{line}"
end
end
end
end
18 changes: 18 additions & 0 deletions lib/httparty/logger/logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
require 'httparty/logger/apache_logger'
require 'httparty/logger/curl_logger'

module HTTParty
module Logger
def self.build(logger, level, formatter)
level ||= :info
format ||= :apache

This comment has been minimized.

Copy link
@thephw

thephw Oct 7, 2014

This line doesn't do anything correct?

This comment has been minimized.

Copy link
@lucasuyezu

lucasuyezu Oct 7, 2014

Author Contributor

Correct. I'll send a fix. However it works when both apache and curl are sent as parameters. Did you experience an error?

This comment has been minimized.

Copy link
@thephw

thephw Oct 7, 2014

Nope, was just looking through the possibility of adding an option to show parameters and wanted to make sure.


case formatter
when :curl
Logger::CurlLogger.new(logger, level)
else
Logger::ApacheLogger.new(logger, level)
end
end
end
end
4 changes: 4 additions & 0 deletions lib/httparty/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@ def encode_body(body)
def handle_response(body, &block)
if response_redirects?
options[:limit] -= 1
if options[:logger]
logger = HTTParty::Logger.build(options[:logger], options[:log_level], options[:log_format])
logger.format(self, last_response)
end
self.path = last_response['location']
self.redirect = true
self.http_method = Net::HTTP::Get unless options[:maintain_method_across_redirects]
Expand Down
5 changes: 5 additions & 0 deletions lib/httparty/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ def initialize(request, response, parsed_block, options={})
@body = options[:body] || response.body
@parsed_block = parsed_block
@headers = Headers.new(response.to_hash)

if request.options[:logger]
logger = ::HTTParty::Logger.build(request.options[:logger], request.options[:log_level], request.options[:log_format])
logger.format(request, self)
end
end

def parsed_response
Expand Down
26 changes: 26 additions & 0 deletions spec/httparty/logger/apache_logger_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'spec_helper'))

describe HTTParty::Logger::ApacheLogger do
describe "#format" do
it "formats a response in a style that resembles apache's access log" do
request_time = Time.new.strftime("%Y-%m-%d %H:%M:%S.%L %z")
log_message = "[HTTParty] [#{request_time}] 302 \"GET http://my.domain.com/my_path\" - "

request_double = double(
:http_method => Net::HTTP::Get,
:path => "http://my.domain.com/my_path"
)
response_double = double(
:code => 302,
:[] => nil
)

logger_double = double
logger_double.should_receive(:info).with(log_message)

subject = described_class.new(logger_double, :info)
subject.current_time = request_time
subject.format(request_double, response_double)
end
end
end
21 changes: 21 additions & 0 deletions spec/httparty/logger/curl_logger_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'spec_helper'))

describe HTTParty::Logger::CurlLogger do
describe "#format" do
it "formats a response in a style that resembles a -v curl" do
request_time = Time.new.strftime("%Y-%m-%d %H:%M:%S.%L %z")

logger_double = double
logger_double.should_receive(:info).with(
/\[HTTParty\] \[#{request_time}\] > GET http:\/\/localhost\n/)

subject = described_class.new(logger_double, :info)
subject.current_time = request_time

stub_http_response_with("google.html")

response = HTTParty::Request.new.perform
subject.format(response.request, response)
end
end
end
22 changes: 22 additions & 0 deletions spec/httparty/logger/logger_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'spec_helper'))

describe HTTParty::Logger do
describe ".build" do
subject { HTTParty::Logger }

it "defaults level to :info" do
logger_double = double()
subject.build(logger_double, nil, nil).level.should == :info
end

it "defaults format to :apache" do
logger_double = double()
subject.build(logger_double, nil, nil).should be_an_instance_of(HTTParty::Logger::ApacheLogger)
end

it "builds :curl style logger" do
logger_double = double()
subject.build(logger_double, nil, :curl).should be_an_instance_of(HTTParty::Logger::CurlLogger)
end
end
end
8 changes: 7 additions & 1 deletion spec/httparty/request_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,13 @@
@request.perform.should == {"hash" => {"foo" => "bar"}}
@request.http_method.should == Net::HTTP::Delete
end

it 'should log the redirection' do
logger_double = double
logger_double.should_receive(:info).twice
@request.options[:logger] = logger_double
@request.perform
end
end

describe "infinitely" do
Expand Down Expand Up @@ -592,4 +599,3 @@
end
end
end

0 comments on commit e885c18

Please sign in to comment.