禁用IP地址日志记录Rails

时间:2014-03-28 06:35:50

标签: ruby-on-rails ruby ruby-on-rails-3 logging ip

我正在尝试在处理请求时禁用IP地址的记录。但我找不到办法做到这一点。我想在用户尚未通过身份验证的应用程序的有限部分禁用IP记录。

所以我的问题是

  

如何禁用特定页面的rails日志中的IP记录(因此IP不会保存在任何日志中)

我正在使用Rails 3.2.17

修改 这是示例日志(来​​自environment.log)

  

开始GET" / my_path"在2014-03-28 11:53:20 +0530

获得192.168.0.109

我不想在日志文件中保存192.168.0.109

3 个答案:

答案 0 :(得分:2)

在config / initializers中,将文件log_fomat.rb添加到:

class ActiveSupport::BufferedLogger
  def formatter=(formatter)
    @log.formatter = formatter
  end
end

class Formatter
  SEVERITY_TO_TAG_MAP     = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'}
  SEVERITY_TO_COLOR_MAP   = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'}
  USE_HUMOROUS_SEVERITIES = true

  def call(severity, time, progname, msg)
    if USE_HUMOROUS_SEVERITIES
      formatted_severity = sprintf("%-3s","#{SEVERITY_TO_TAG_MAP[severity]}")
    else
      formatted_severity = sprintf("%-5s","#{severity}")
    end

    formatted_time = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3)
    color = SEVERITY_TO_COLOR_MAP[severity]

    "\033[0;37m#{formatted_time}\033[0m [\033[#{color}m#{formatted_severity}\033[0m] #{msg.strip} (pid:#{$$})\n"
  end

end

Rails.logger.formatter = Formatter.new

参考文献:

  1. http://rubyjunky.com/cleaning-up-rails-4-production-logging.html
  2. http://cbpowell.wordpress.com/2012/04/05/beautiful-logging-for-ruby-on-rails-3-2/
  3. Rails logger format string configuration

答案 1 :(得分:1)

最后通过使用emaillenin的回答而不是 emaillenin 来做到这一点:D。

这是解决方案

  # Overriding Rails logger to not save IP addresses for specific paths
  # Put this file in <app_root>/config/initializers

  # defining setter for Rails default log formatter, so later we can set our custom logger using '='
  class ActiveSupport::BufferedLogger
    def formatter=(formatter)
      @log.formatter = formatter
    end
  end

  # Modified Formatter Class with custom 'call' method
  class Formatter
    Format = "%s\n"
    # Remove IP while getting request on below specified Path
    FilteredActionRegexp = /app_path|another_path/i

    # reference for regexp of IP address
    # http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/
    IPRegexp = /\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/
    FilteredString = '**FILTERED**'

    def call(severity, time, progname, msg)
      Format % [msg2str(filter_ip(msg))]
    end

    private

    def msg2str(msg)
      case msg
      when ::String
        msg
      when ::Exception
        "#{ msg.message } (#{ msg.class })\n" <<
          (msg.backtrace || []).join("\n")
      else
        msg.inspect
      end
    end

    # Replace IP Address with custom string if action is filtered
    def filter_ip(msg)
      # Replace only if message contains filtered action
      if msg =~ FilteredActionRegexp
        # If log string contains IP address then remove it with custom string
        msg.gsub(IPRegexp, FilteredString )
      else
        msg
      end
    end
  end

  # Override Rails default logger formatter
  Rails.logger.formatter = Formatter.new

答案 2 :(得分:0)

我使用Lograge

  

Taming Rails的默认请求记录

而不是像这样具有不可分析的日志输出量:

Started GET "/" for 127.0.0.1 at 2012-03-10 14:28:14 +0100
Processing by HomeController#index as HTML
  Rendered text template within layouts/application (0.0ms)
  Rendered layouts/_assets.html.erb (2.0ms)
  Rendered layouts/_top.html.erb (2.6ms)
  Rendered layouts/_about.html.erb (0.3ms)
  Rendered layouts/_google_analytics.html.erb (0.4ms)
Completed 200 OK in 79ms (Views: 78.8ms | ActiveRecord: 0.0ms)

你得到一行包含所有重要信息,如:

method=GET path=/jobs/833552.json format=json controller=jobs action=show status=200 duration=58.33 view=40.43 db=15.26