How to set log level in faraday

kauschan picture kauschan · Sep 16, 2014 · Viewed 10.3k times · Source

I recently switched my http client to faraday and everything works as intended. I have the following piece of code to create a connection:

@connection = Faraday.new(:url => base_url) do |faraday|
              faraday.use Custim::Middleware
              faraday.request :url_encoded             # form-encode POST params
              faraday.request :json
              faraday.response :json, :content_type => /\bjson$/
              faraday.response :logger
              faraday.adapter Faraday.default_adapter  # make requests with Net::HTTP

The faraday logger helps print all the logs on the console output. However i do not want to print all log levels on the console output. How do i set the log level to just print say the error logs ? .

i am using faraday version 0.8.9

Answer

Kelvin picture Kelvin · May 19, 2015

There is a way, but it doesn't seem to be documented at all. I tried this on 0.9.1, but it should work on 0.8.9 too.

# provide your own logger
logger = Logger.new $stderr
logger.level = Logger::ERROR
Faraday.new(:url => base_url) do |faraday|
  # ...
  faraday.response :logger, logger
  # ...
end

This works because faraday.response :logger probably creates a middleware using Faraday::Response::Logger, which has this constructor:

def initialize(app, logger = nil)

Bonus

In 0.9.1, the constructor signature is

def initialize(app, logger = nil, options = {})

The class also contains this: DEFAULT_OPTIONS = { :bodies => false } which probably means you can pass a :bodies option after the logger to control logging of the body. Apparently you can even use {bodies: {response: true}} to log response bodies but not request bodies.