Elise
Elise

Reputation: 5144

Custom logger formatter in HTTParty

I would like to include automatic logging to my HTTParty requests, as part of a CLI app built with Thor.

I'm aware of debug_output $stdout, but the default formatters (:apache and :curl) do so much more than I want. I'd like to have extremely minimal logging that just outputs the request endpoint, params, and the response, along the lines of

PUT /users/123

{
  email: [email protected]
}

RESPONSE 201

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

I can see from HTTParty's specs that the Logger has an add_formatter method, which makes me wonder whether I can build a custom formatter, eg SimpleFormatter, and attach it to my class with something like

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

But the example formatters in the source don't seem to subclass anything, so I'm unsure what interface my custom formatter should comply with.

Upvotes: 1

Views: 1187

Answers (1)

Rots
Rots

Reputation: 5586

Cool idea.

You need to implement initialize(logger, level) and format(request, response) as per the sample curl and apache samples. Then you can add it to the formatters.

There's some properties you can use as well, but they don't seem to be mandatory.

attr_accessor :level, :logger, :current_time

I had a little play with the httparty example to see if it works, seems to work fine. Here's my sample and output.

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

output:

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

Upvotes: 2

Related Questions