HTTParty 中的自定义记录器格式化程序

Custom logger formatter in HTTParty

我想将自动记录到我的 HTTParty 请求中,作为使用 Thor 构建的 CLI 应用程序的一部分。

我知道 debug_output $stdout,但默认格式化程序(:apache:curl)做的比我想要的多得多。我想要极少的日志记录,只输出请求端点、参数和响应,按照

PUT /users/123

{
  email: example@email.com
}

RESPONSE 201

{
  user: {
    id: 123,
    email: example@email.com
  }
}

我可以从 HTTParty 的规范中看到 Logger 有一个 add_formatter 方法,这让我想知道我是否可以构建一个自定义格式化程序,例如 SimpleFormatter,并将其附加到我的 [=25] =] 类似

class API
  include HTTParty
  logger ::Logger.new("my simple logger"), :debug, :SimpleFormatter
end

但是源代码中的示例格式化程序似乎没有子class任何东西,所以我不确定我的自定义格式化程序应该符合什么接口。

好主意。

您需要根据示例 curl 和 apache 示例实施 initialize(logger, level)format(request, response)。然后你可以将它添加到格式化程序中。

您也可以使用一些属性,但它们似乎不是强制性的。

attr_accessor :level, :logger, :current_time

我试了一下 httparty 示例,看它是否有效,似乎工作正常。这是我的示例和输出。

party.rb

require 'httparty'
require 'logger'
require './custom_formatter.rb'

HTTParty::Logger.add_formatter('custom', HTTParty::Logger::CustomFormatter)

# Or wrap things up in your own class
class StackExchange
  include HTTParty
  logger ::Logger.new("a logger"), :debug, :custom
  base_uri 'api.stackexchange.com'

  def initialize(service, page)
    @options = { query: {site: service, page: page} }
  end

  def questions
    self.class.get("/2.2/questions", @options)
  end

  def users
    self.class.get("/2.2/users", @options)
  end
end

stack_exchange = StackExchange.new("Whosebug", 1)
puts stack_exchange.questions
puts stack_exchange.users

custom_formatter.rb

module HTTParty
  module Logger
    class CustomFormatter 

      attr_accessor :level

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

      def format(request, response)
        @logger.send @level, "hahahahaha "
      end
    end
  end
end

输出:

--> D, [2016-06-02T22:30:26.613721 #5844] DEBUG -- : hahahahaha 
--> D, [2016-06-02T22:30:27.440348 #5844] DEBUG -- : hahahahaha