Filtering parts or all of request URL from rails logs

拥有回忆 提交于 2019-12-22 09:50:12

问题


Rails provides filter_parameter_logging to filter sensitive parameters from the rails log.

If you have a a JSONP API, some sensitive information could be present in the URL. Is there a way to filter request URLS from the log also?


回答1:


Note: The answer here was the way to get it work on Rails 2.x ~> 3.0. Starting from Rails 3.1, if you set config.filter_parameters, Rails will filter out the sensitive parameter in the query string as well. See this commit for more detail.


I think in that case, you need to override complete_request_uri in ActionController::Base, since ActionController::Benchmarking calls that method and prints the line that looks like:

Completed in 171ms (View: 35, DB: 7) | 200 OK [http://localhost:3000/]

I think you can put this in initializer to override this method

class ActionController::Base
  private

  def complete_request_uri
    "#{request.protocol}#{request.host}#{request.request_uri.gsub(/secret=([a-z0-9]+)/i, "secret=[FILTERTED]")}"
  end
end

Note that you need to play a bit with regular expression to make it substitute the portion you wanted.




回答2:


Sadly this no longer works in Rails 3. The path (including query parameters) comes from ActionDispatch::Request, which inherits from Rack::Request. Here's the relevant monkeypatch that you can throw into an initializer:

class ActionDispatch::Request
  def fullpath
    @fullpath ||= super.gsub(/secret=[^&]+/, 'secret=[FILTERED]')
  end
end

I switched to using [^&] in the regex since the parameter could easily have characters that aren't letters or numbers in it.



来源:https://stackoverflow.com/questions/2062405/filtering-parts-or-all-of-request-url-from-rails-logs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!