简体   繁体   中英

How to filter sensitive information when logging with Sinatra and Rack Logger

I maintain a Sinatra app that acts as a JSON API service. The API is consumed by another web app, as well as a mobile app.

I'd like to have Rack::CommonLogger exclude sensitive information, like a password, from its logs. Rails has this setting enabled, but I have found no documentation how to do this in Sinatra.

You can try to intercept the call to write and filter out sensitive messages like so :

logger = Logger.new("my_common.log")
logger.instance_eval do
  def write(msg)
    self.send(:<<, msg) if !msg.match /SUPER SENSITIVE INFO HERE/
  end
end

then, configure Rack::CommonLogger to use this instance of the logger:

config.middleware.use Rack::CommonLogger, logger

Sinatra logs to STDERR which is an IOm but we don't want to store other peoples passwords:

module NoTokenLogging
  def write(*args)
    args.first.sub!(/password=\S+/, "password=[FILTERED]")
    super
  end
end
IO.prepend NoTokenLogging

You can also just leverage ActiveSupport::ParameterFilter .

https://edgeapi.rubyonrails.org/classes/ActiveSupport/ParameterFilter.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM