How to set log level in faraday
Asked Answered
F

3

7

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

Fanatical answered 16/9, 2014 at 18:8 Comment(2)
I did not find that any useful info was being output to the system logs by Faraday. I found the "Faraday Detailed Logger" gem helpful github.com/envylabs/faraday-detailed_loggerOlericulture
It's been nearly 10 years since this was asked, and Googling for "ruby faraday logger" returns this question as the 3rd match. The 1st & 2nd matches are official docs but aren't very helpful. Go figure.Bronny
B
15

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.

Bronny answered 19/5, 2015 at 16:29 Comment(0)
C
3

Overriding the logger.debug method did the trick for me. Now I only get messages for INFO and above. I'm using faraday 0.12.1.

faraday = Faraday.new(:url => "http://example.org") do |faraday|
  faraday.response :logger do | logger |
    def logger.debug *args; end
  end
end

It's a little bit dirty but a whole lot less code ;)

Chore answered 27/6, 2017 at 3:12 Comment(0)
S
2

I don't think there's a native way to do this in Faraday, but it'd be easy to implement in middleware:

require 'faraday'

class LogOnError < Faraday::Response::Middleware
  extend Forwardable
  def_delegators :@logger, :debug, :info, :warn, :error, :fatal

  ClientErrorStatuses = 400...600

  def initialize(app, options = {})
    @app = app
    @logger = options.fetch(:logger) {
      require 'logger'
      ::Logger.new($stdout)
    }
  end

  def call(env)
    @app.call(env).on_complete do
      case env[:status]
      when ClientErrorStatuses
        info "#{env.method} #{env.url.to_s} #{response_values(env)}"
      end
    end
  end


  def response_values(env)
    {:status => env.status, :headers => env.response_headers, :body => env.body}
  end
end

conn = Faraday.new('https://github.com/') do |c|
  c.use LogOnError
  c.use Faraday::Adapter::NetHttp
end

puts "No text to stdout"
response = conn.get '/' #=> No text to stdout]
puts "No text above..."
puts "Text to stdout:"
response = conn.get '/cant-find-me' #=> Text to standoupt

Which produces:

No text to stdout
No text above...
Text to stdout:
I, [2014-09-17T14:03:36.383722 #18881]  INFO -- : get https://github.com/cant-find-me {:status=>404, :headers=>{"server"=>"GitHub.com", "date"=>"Wed, 17 Sep 2014 13:03:36 GMT", "content-type"=>"application/json; charset=utf-8", "transfer-encoding"=>"chunked", "connection"=>"close", "status"=>"404 Not Found", "x-xss-protection"=>"1; mode=block", "x-frame-options"=>"deny", "content-security-policy"=>"default-src *; script-src assets-cdn.github.com www.google-analytics.com collector-cdn.github.com; object-src assets-cdn.github.com; style-src 'self' 'unsafe-inline' 'unsafe-eval' assets-cdn.github.com; img-src 'self' data: assets-cdn.github.com identicons.github.com www.google-analytics.com collector.githubapp.com *.githubusercontent.com *.gravatar.com *.wp.com; media-src 'none'; frame-src 'self' render.githubusercontent.com gist.github.com www.youtube.com player.vimeo.com checkout.paypal.com; font-src assets-cdn.github.com; connect-src 'self' ghconduit.com:25035 live.github.com uploads.github.com s3.amazonaws.com", "vary"=>"X-PJAX", "cache-control"=>"no-cache", "x-ua-compatible"=>"IE=Edge,chrome=1", "set-cookie"=>"logged_in=no; domain=.github.com; path=/; expires=Sun, 17-Sep-2034 13:03:36 GMT; secure; HttpOnly", "x-runtime"=>"0.004330", "x-github-request-id"=>"2EED8226:76F6:1951EDA:541986A8", "strict-transport-security"=>"max-age=31536000; includeSubdomains; preload", "x-content-type-options"=>"nosniff"}, :body=>"{\"error\":\"Not Found\"}"}

You can split this off into it's own class that you include to clean it up a bit.

Sinistrodextral answered 17/9, 2014 at 13:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.