2016-06-02 5 views
1

Thorで構築されたCLIアプリケーションの一部として、HTTPartyリクエストに自動ロギングを含めたいと思います。HTTPartyのカスタムロガーフォーマッター

私はdebug_output $stdoutを認識していますが、デフォルトのフォーマッタ(:apacheと)は私が望む以上に多くのことをしています。私はこれが私を行い、Loggerはadd_formatterメソッドを持っているHTTPartyのスペックから

PUT /users/123 

{ 
    email: [email protected] 
} 

RESPONSE 201 

{ 
    user: { 
    id: 123, 
    email: [email protected] 
    } 
} 

私が見ることができるの線に沿って、非常に最小限だけのparams、要求エンドポイントを出力し、ロギング、および応答をしたいのですが私は、カスタムフォーマッタを構築するなどSimpleFormatter、および

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

ようなもので私のクラスに添付できるかどうかを疑問に思う。しかし、ソースの例フォーマッタは何をサブクラス化していないようですので、私はどのようなインターフェースわかりませんよ私のカスタムフォーマッタは遵守する必要があります。

答えて

2

クールなアイデア。

サンプルのカールと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("stackoverflow", 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