httparty:如何记录请求?

36

我该如何记录使用httparty发送的请求?

HTTParty.post(
          @application_url,
          :headers => {
            "Accept"        => "application/json",
            "Content-Type"  => "application/json; charset=utf-8"
          },
          :body => {
            "ApplicationProfileId" => application.applicationProfileId
          }.to_json
        )
3个回答

70

在类级别上使用debug_output

class Foo
  include HTTParty
  debug_output $stdout
end

或按请求

response = HTTParty.post(url, :body => body, :debug_output => $stdout)

1
很好,似乎没有其他人知道如何按请求执行它。 - Jaco Pretorius
8
注意:如果你深入了解一下Net::HTTP库的内部结构,你就会意识到它不应该在生产环境中使用。https://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTP.html#method-i-set_debug_output - hatenine
1
我会建议这样写: SomeLogger.info(HTTParty.get(uri, query: parameters).request.last_uri) - hatenine

6

您可以使用内置日志记录器:

my_logger = Rails.logger || Logger.new # use what you like
my_logger.info "The default formatter is :apache. The :curl formatter can also be used."
my_logger.info "You can tell which method to call on the logger too. It is info by default."

HTTParty.get "http://google.com", logger: my_logger, log_level: :debug, log_format: :curl

4
使用类级别的 debug_output 方法设置输出流,使得调试信息被发送到该流中。

2
能否在 debug_output 中使用 Rails.logger - Vishal Vijay
1
debug_output Rails.logger 在 Rails 4 中可用,但在 Rails 3 中不可用(显然,Rails 3 版本缺少 << 运算符的实现)。 - GuyPaddock
1
@VishalVijay:这在Rails 3中可以工作,尽管格式与debug_output略有不同:logger Rails.logger, :debug, :curl - GuyPaddock
谢谢。我会尝试这个。 - Vishal Vijay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接