如何在法拉第设置日志级别

时间:2014-09-16 18:08:32

标签: ruby-on-rails ruby faraday

我最近将我的http客户端切换到法拉第,一切都按预期工作。我有以下代码来创建连接:

@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

法拉第记录器有助于打印控制台输出上的所有日志。但是我不想在控制台输出上打印所有日志级别。如何设置日志级别只打印说错误日志? 。

我正在使用法拉第版本0.8.9

3 个答案:

答案 0 :(得分:9)

有一种方法,但它似乎根本没有记录。我在0.9.1上试过这个,但它也应该在0.8.9上运行。

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

这是有效的,因为faraday.response :logger可能使用Faraday::Response::Logger创建一个中间件,它具有以下构造函数:

def initialize(app, logger = nil)

<强>加成

在0.9.1中,构造函数签名是

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

该类还包含:DEFAULT_OPTIONS = { :bodies => false },这可能意味着您可以在记录器之后传递:bodies选项来控制正文的记录。显然,您甚至可以使用{bodies: {response: true}}来记录响应主体,但不能使用请求主体。

答案 1 :(得分:2)

我认为在法拉第中没有本地方法可以做到这一点,但在中间件中实现起来很容易:

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

产生:

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\"}"}

你可以把它拆分成你自己的类include来清理它。

答案 2 :(得分:0)

覆盖categories方法对我来说很有用。现在我只收到logger.debug及以上的消息。我正在使用法拉第0.12.1。

INFO

它有点脏,但代码少得多;)