0

I'm doing some custom logging in my Rails application and I want to automatically sensor some parameters. I know that we have fitler_parameter_logging.rb which does this for the params object. How can I achieve something like this for my custom hash.

Let's say I'm logging something like this:

Rails.logger.info {name: 'me', secret: '1231234'}.inspect

So my secret key should be sensored in the logs.

I know I can personally delete the key before logging, but it adds noise to my application.

aks
  • 8,796
  • 11
  • 50
  • 78

1 Answers1

0

The question title talks about removing the parameters, but your question refers to censoring the parameters similar to how Rails.application.config.filter_parameters works. If it's the latter, it looks like that's already been answered in Manually filter parameters in Rails. If it's the former, assuming a filter list, and a hash:

FILTER_LIST = [:password, :secret]
hash = {'password' => 123, :secret => 321, :ok => "this isn't going anywhere"}

then you could do this:

hash.reject { |k,v| FILTER_LIST.include?(k.to_sym) }

That'll cope with both string and symbol key matching, assuming the filter list is always symbols. Additionally, you could always use the same list as config.filter_parameters if they are going to be the same and you don't need a separate filter list:

hash.reject { |k,v| Rails.application.config.filter_parameters.include?(k.to_sym) }

And if you wanted to make this easier to use within your own logging, you could consider monkey patching the Hash class:

class Hash
  def filter_like_parameters
    self.reject { |k,v| Rails.application.config.filter_parameters.include?(k.to_sym) }
  end
end

Then your logging code would become:

Rails.logger.info {name: 'me', secret: '1231234'}.filter_like_parameters.inspect

If you do monkey patch custom functionality to core classes like that though for calls you're going to be making a lot, it's always best to use a quite obtuse method name to reduce the likelihood of a clash with any other library that might share the same method names.

Hope that helps!

ejdraper
  • 439
  • 2
  • 6
  • Cool, I understand this. Now will I need to call the reject everytime before logging the hash? – aks Jan 13 '18 at 18:13
  • Just updated the answer above to include an example about monkey patching that filter functionality to the `Hash` class so as to be able to more easily use it in all of your logging code. – ejdraper Jan 13 '18 at 18:21