2016-06-02 2 views
1

Thor로 작성된 CLI 응용 프로그램의 일부로 HTTParty 요청에 자동 로깅을 포함하고 싶습니다.HTTParty의 사용자 정의 로거 포맷터

저는 debug_output $stdout을 알고 있지만 기본 포맷터 (:apache 및)는 제가 원하는 것보다 훨씬 많은 것을합니다. 나는 어느 날하게, 로거는 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

멋진 아이디어.

샘플 컬 및 아파치 샘플에 따라 initialize(logger, level)format(request, response)을 구현해야합니다. 그런 다음 포맷터에 추가 할 수 있습니다.

사용할 수있는 몇 가지 속성이 있지만 필수 항목은 아닙니다.

attr_accessor :level, :logger, :current_time 

제대로 동작하는지 확인하기 위해 httpaty 예제와 약간의 플레이가있었습니다. 여기 내 샘플과 출력이 있습니다.

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 
관련 문제